Notice
Recent Posts
Recent Comments
Link
먼지나는 블로그
Kotlin Collection 개념 본문
Collection Type
val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five") // this is OK
//numbers = mutableListOf("six", "seven") // compilation error
mutable list : 추가나 삭제 등 수정이 가능한 리스트
inmutable list : 수정이 불가능한 리스트 // add 함수 사용 시 동작하지 않음
List
데이터가 저장되거나 삭제될 때 순서를 보장하는 컬렉션타입
val numbers = listOf("one", "two", "three", "four")
println("Number of elements: ${numbers.size}")
println("Third element: ${numbers.get(2)}")
println("Fourth element: ${numbers[3]}")
println("Index of element \"two\" ${numbers.indexOf("two")}")
set
동일한 데이터가 존재할 수 없는 집합 ( 순서보장X 중복될 수 없음 )
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")
if (numbers.contains(1)) println("1 is in the set")
val numbersBackwards = setOf(4, 3, 2, 1)
println("The sets are equal: ${numbers == numbersBackwards}")
map
map에 저장되는 데이터는 key-value 형식의 타입을 가지게 됨 ( 중복될 수 없음 )
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")
if ("key2" in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}")
if (1 in numbersMap.values) println("The value 1 is in the map")
if (numbersMap.containsValue(1)) println("The value 1 is in the map") // same as previous
Constructing collections
val numbersSet = setOf("one", "two", "three", "four")
val emptySet = mutableSetOf<String>()
numberSet은 현재 inmutable 타입이므로 더이상의 데이터 추가나 수정이 불가능함. 또한 set는 중복된 데이터가 존재할 수 없기 때문에 각기 다른 네개의 값을 가지고 있는 상황
emptySet은 mutable 타입이기 때문에 데이터 추가/수정이 가능하지만 아무런 인자도 들어있지 않은 상황
val empty = emptyList<String>()
위에 있는 emptySet와 같은 결과값이 반환되지만 두 변수모두 어떠한 인자도 들어있지 않은 상황에서 좀 더 직관적으로 알아보기 쉽기 때문에 다른 이름으로도 이용함
https://kotlinlang.org/docs/collection-operations.html#common-operations
Collection operations overview | Kotlin
kotlinlang.org
'내맘대로 공부 > kotlin' 카테고리의 다른 글
kotlin firebase 설정 및 로그인 구현 (0) | 2021.07.15 |
---|---|
BMI 계산기 구현 (0) | 2021.07.10 |
Kotlin 개발 vs Java 개발 (0) | 2021.07.05 |
kotlin 문법 훑어보기 (+추가) (1) | 2021.07.05 |