Do it! 코틀린 프로그래밍 [셋째마당, 코틀린 표준 라이브러리의 활용] 학습
컬렉션(Collection)이란? 자주 사용하는 기초적인 자료구조를 모아 놓은 일종의 프레임워크
📌 코틀린의 컬렉션
컬렉션 | 불변형(읽기전용) | 가변형 |
---|---|---|
List | listOf | mutableListOf, arrayListOf |
Set | setOf | mutableSetOf, hashSetOf, linkedSetOf, sortedSetOf |
Map | mapOf | mutableMapOf, hashMapOf, linkedMapOf, sortedMapOf |
List란? 순서에 따라 정렬된 요소를 가지는 컬렉션
📌 listOf 함수
public fun <T> listOf(vararg elements: T): List<T>
<T>
는 자료형을 지정하지 않으면 <Any>
가 기본값📌 컬렉션 반복하기
.indices
멤버를 추가하면 됨fun main() {
val fruits = listOf("apple", "banana", "kiwi")
for(item in fruits)
println(item)
// 인덱스를 통한 접근
for(index in fruits.indices)
println("fruits[$index] = ${fruits[index]}")
}
📌 emptyList() 함수
val emptyList: List<String> = emptyList<String>()
📌 listOfNotNull() 함수
val nonNullsList: List<Int> = listOfNotNull(2, 45, 2, null, 5, null)
// nonNUllsList = [2, 45, 2, 5] 로 생성
📌 arrayListOf() 함수
public fun <T> arrayListOf(vararg element: T): ArrayList<T>
add()
와 remove()
를 통해 요소를 추가하거나 삭제📌 가변형 mutableListOf() 함수
public fun <T> mutableListOf(vararg elements: T): MutableList<T>
add()
와 removeAt()
메서드를 통해 요소를 추가, 삭제toMutableList()
를 사용하여 가변형으로 변경 가능fun main() {
val fruits = listOf("apple", "banana", "kiwi") // 불변형 List
val mutableFruits = fruits.toMutableList() // 새로운 가변형 List 생성
mutableFruits.add("grape") // 가변형 List에 요소 추가
}
📌 List와 배열의 차이
Array<T>
Array<T>
와 MutableList<T>
는 제네릭 관점에서 상·하위 자료형 관계가 성립하지 않는 무변성Array<Int>
와 Array<Number>
는 무관List<T>
List<T>
와 MutableList<T>
는 인터페이스로 설계되어 하위에서 특정한 자료구조로 구현함. 따라서 해당 자료구조에 따라 성능이 달라짐List<T>
는 공변성List<Int>
가 List<Number>
에 지정될 수 있음Set 이란? 정해진 순서가 없는 요소들의 집합
중복된 요소를 가질 수 없음 -> 모든 요소가 유일(unique)해야 함
Map 이란? 요소를 키와 값의 쌍 형태로 저장
키는 중복될 수 없고 유일하지만, 값은 중복해서 사용 가능
📌 불변형 setOf() 함수
Set<T>
를 반환fun main() {
val mixedTypeSet = setOf("Hello", 5, "world", 4.14, 'c') // 자료형 혼합 초기화
// mixedTypeSet = [Hello, 5, world, 4.14, c]
var intSet: Set<Int> = setOf<Int>(1, 5, 5)
// intSet = [1, 5] -> 중복 허용X
}
📌 가변형 mutableSetOf() 함수
fun main() {
val animals = mutableSetOf("Lion", "Dog", "Cat", "Python", "Hippo")
animals.add("Lion") // 이미 존재하는 요소이므로 변화 없음
animals.remove("Python") // Python 삭제
}
📌 hashSetOf() 함수
fun main() {
val intHashSet: HashSet<Int> = hashSetOf(6, 3, 4, 7)
intsHashSet.add(5)
intsHashSet.remove(6)
// intHashSet = [3, 4, 5, 7]
// 입력 순서와 중복된 요소를 무시
}
📌 sortedSetOf() 함수
📌 linkedSetOf() 함수
📌 불변형 mapOf() 함수
val map: Map<키 자료형, 값 자료형> = mapOf(키 to 값[...])
fun main() {
val langMap: Map<Int, String> = mapOf(11 to "Java", 22 to "Kotlin", 33 to "C++")
// 여기서 22는 인덱스가 아닌 키값
println("langMap[22] = ${langMap[22]}")
}
📌 가변형 mutableMapOf() 함수
put(키, 값)
형태로 요소를 추가remove(키)
형태로 요소를 삭제fun main() {
val capitalCityMap: MutableMap<String, String> = mutableMapOf("Korea" to "Seoul", "China" to "Beijing")
capitalCityMap.put("UK", "London")
// capitalCityMap["UK"] = "London" 처럼 사용 가능
capitalCityMap.remove("China") // 키값으로 제거
val addData = mutableListOf("USA" to "Washington")
// putAll() 메서드를 사용하여 capitalCityMap에 addData를 병합
capitalCityMap.putAll(addData)
}