list, set, map
Immutable Collection
: 변경할 수 없는 값
1. List
var numberList = listOf<Int>(1, 2, 3)

2. Set(집합)
- 중복되는 수는 한번만 출력(중복 허용X)
- 순서가 없다. (index가 존재하지 않는다)
val numberSet = setOf<Int>(1, 2, 3, 3, 3)

3. Map
- key, value 방식
val numberMap = mapOf<String, Int>("one" to 1, "two" to 2, "three" to 3)
println(numberMap.get("one")) // 출력 결과 : 1
Mutable Collection(변경 가능)
val numList = mutableListOf<Int>(1, 2, 3)
numList.add(3, 4)
// 결과 : [1, 2, 3, 4]
val numSet = mutableSetOf<Int>(1, 2, 3, 4, 4, 4)
numSet.add(10)
// 결과 : [1, 2, 3, 4, 10]
val numMap = mutableMapOf<String, Int>("one" to 1)
numMap.put("two", 2)
// 결과 : {one=1, two=2}
Mutable Collection의 값 추가/삭제
- 삭제 : removeAt( index ), remove( element )
1. mutableListOf
val a = mutableListOf<Int>(1, 2, 3)
a.add(4) // 결과 : [1, 2, 3, 4]
a.add(0, 100) // 값이 추가됨. 결과 : [100, 1, 2, 3, 4]
a.set(0, 200) // 결과 : [200, 1, 2, 3, 4]
a.removeAt(1) // 인덱스 1의 데이터 삭제. 결과 : [200, 2, 3, 4]
2. mutableSetOf
val b = mutableSetOf<Int>(1, 2, 3, 4)
b.add(2) // 순서가 없고, 중복을 허용하지 않기 때문에 변화없다.
// 결과 : [1, 2, 3, 4]
b.remove(2) // element값 삭제. 결과 : [1, 3, 4]
b.remove(5) // 없는 값을 없애도 에러가 일어나지 않는다.
3. mutableMapOf
val c = mutableMapOf<String, Int>("one" to 1)
c.put("two", 2) // 결과 : {one=1, two=2}
c.replace("two", 3) // 결과 : {one=1, two=3}
println(c.keys) // 결과 : [one, two]
println(c.values) // 결과 : [1, 3]
c.clear() // c 값 전부 삭제
'안드로이드 > 코틀린' 카테고리의 다른 글
| [코틀린] 04. 배열 (0) | 2021.09.03 |
|---|---|
| [코틀린] 엘비스 연산자 (0) | 2021.08.23 |
| [코틀린] 03. 연산자와 제어흐름 (0) | 2021.08.23 |
| [코틀린] 02. 함수 (0) | 2021.08.23 |
| [코틀린] 01. 변수 (0) | 2021.08.22 |