출처: https://www.boostcourse.org/mo234/lecture/154316?isDesc=false
package chap05.section2
fun main() {
val mixedTypeSet = setOf("Hello", 5, "world", 3.14, 'c')
val intSet: Set<Int> = setOf<Int>(1, 4, 5, 5, 5)
println(mixedTypeSet)
println(intSet) // 중복된 요소 중에 하나만 출력
}
[Hello, 5, world, 3.14, c]
[1, 4, 5]
package chap05.section2
fun main() {
val animals = mutableSetOf("Lion", "Dog", "Cat", "Python", "Hippo")
animals.add("Dog") // 이미 존재하므로 변화 없음.
println(animals)
animals.remove("Python")
println(animals)
}
[Lion, Dog, Cat, Python, Hippo]
[Lion, Dog, Cat, Hippo]
cf) 해시 테이블: 내부적으로 키와 인덱스를 이용해 검색과 변경 등을 매우 빠르게 처리할 수 있는 자료구조
위의 그림에서 해시 함수를 통해 key에 해당하는 bucket을 빠르게 찾을 수 있다.
package chap05.section2
fun main() {
val intHashSet: HashSet<Int> = hashSetOf(6, 3, 4, 7) // 불변성이 없음.
intHashSet.add(5)
intHashSet.remove(6)
println(intHashSet)
}
[3, 4, 5, 7]
이진 탐색 트리가 한쪽으로 치우친 트리 구조일 경우, 트리 높이 만큼 시간이 걸리는 최악의 경우가 발생할 수 있다.
레드-블랙 트리는 이 단점을 Red와 Black의 색상으로 치우친 결과 없이 구분되게 해서, 최악의 경우에도 검색 등의 처리에서 일정 시간을 보장해주는 자료구조이다.
package chap05.section2
import java.util.*
fun main() {
val intSortedSet: TreeSet<Int> = sortedSetOf(4, 1, 7, 2)
intSortedSet.add(6)
intSortedSet.remove(1)
println("intSortedSet = $intSortedSet") // 오름차순 정렬된 결과
intSortedSet.clear()
println("intSortedSet = $intSortedSet")
}
intSortedSet = [2, 4, 6, 7]
intSortedSet = []
val map: Map<key type, value type> = mapOf(key to value [, ...])
package chap05.section2
fun main() {
val langMap: Map<Int, String> = mapOf(11 to "Java", 22 to "Kotlin", 33 to "C++")
for((key, value) in langMap){
println("key = $key, value = $value")
}
println("langMap[22] = ${langMap[22]}")
println("langMap.get(22) = ${langMap.get(22)}")
println("langMap.keys = ${langMap.keys}") // 맵의 모든 키 출력 (읽기 전용 Set 반환)
}
key = 11, value = Java
key = 22, value = Kotlin
key = 33, value = C++
langMap[22] = Kotlin
langMap.get(22) = Kotlin
langMap.keys = [11, 22, 33]
package chap05.section2
fun main() {
val capitalCityMap: MutableMap<String, String>
= mutableMapOf("Korea" to "Seoul", "China" to "Beijing", "Japan" to "Tokyo")
println(capitalCityMap.keys)
println(capitalCityMap.values)
capitalCityMap.put("UK", "London")
capitalCityMap.remove("China")
println(capitalCityMap)
val addData = mutableMapOf("USA" to "Washington")
capitalCityMap.putAll(addData) // 맵 자체를 추가
println(capitalCityMap)
}
[Korea, China, Japan]
[Seoul, Beijing, Tokyo]
{Korea=Seoul, Japan=Tokyo, UK=London}
{Korea=Seoul, Japan=Tokyo, UK=London, USA=Washington}
package chap05.section2
import java.util.SortedMap
fun main() {
val hashMap: HashMap<Int, String> = hashMapOf(1 to "Hello", 2 to "World")
println("hashMap: $hashMap")
val sortedMap: SortedMap<Int, String> = sortedMapOf(2 to "Apple", 1 to "Banana")
println("sortedMap: $sortedMap") // 키에 대해 오름차순 정렬
val linkedHashMap: LinkedHashMap<Int, String> = linkedMapOf(1 to "Computer", 2 to "Mouse")
println("linkedHashMap: $linkedHashMap")
}
hashMap: {1=Hello, 2=World}
sortedMap: {1=Banana, 2=Apple}
linkedHashMap: {1=Computer, 2=Mouse}
햄버거 Set 한 개요~