Kotlin 앱 프로그래밍

kotlin에서 리스트와 맵 예제

쿠카이든 2023. 5. 20. 21:30
728x90

 

  • 코틀린에서는 가변과 불편이라는 2가지 타입의 클래스를 제공한다.
    • List는 불변 타입이므로 size(), get() 함수만 제공하고 데이터를 추가하거나 변경하는 add(), set() 함수는 제공하지 않는다.
    • 그런데, MutableList는 가변타입이므로 size(), get() 함수 이외에 add(), set() 함수를 이용할 수 있다.
      • MutableList는 mutableListOf() 함수로 만들 수 있다.
fun main() {
    var mutableList = mutableListOf<Int>(10,20,30)
    mutableList.add(3,40)
    mutableList.add(0,50)
    
    println(
    	"""
        list size : ${mutableList.size}
        list data : ${mutableList[0]}, ${mutableList.get(1)}, ${mutableList.get(2)}, ${mutableList.get(3)}
        """
    )
}
728x90

 

  • Map 객체는 키와 값으로 이루어진 데이터의 집합이다. 
    • Map 객체의 키와 값은 Pair 객체를 이용할 수도 있고 '키 to 값' 형태로 이용할 수도 있다.
fun main() {
    var map = mapOf<String, String>(Pair("one", "hello"), "two" to "world")
    println(
    	"""
        map size : ${map.size}
        map data : ${map.get("one")}, ${map.get("two")}
        """
    )
}
728x90