<aside> <img src="https://prod-files-secure.s3.us-west-2.amazonaws.com/904e5e50-75a6-4c6d-807c-5c432db9bb0f/cbf1bb0a-1633-4e02-96ff-ff688e28004d/Kotlin_Icon_2021.svg.png" alt="https://prod-files-secure.s3.us-west-2.amazonaws.com/904e5e50-75a6-4c6d-807c-5c432db9bb0f/cbf1bb0a-1633-4e02-96ff-ff688e28004d/Kotlin_Icon_2021.svg.png" width="40px" /> 3장 목차
</aside>
fun main() {
val set = hashSetOf(1, 2, 3)
val list = arrayListOf(1, 2, 3)
val map = hashMapOf(1 to "one", 7 to "seven", 10 to "ten")
println(set.javaClass)
println(list.javaClass)
println(map.javaClass)
}
//출력값
//class java.util.HashSet
//class java.util.ArrayList
//class java.util.HashMap
val list = listOf(1, 2, 3)
println(list) //출력값 [1, 2, 3]
toString()
가 디폴트로 구현되어있다.
fun main() {
val list = listOf(1, 2, 3)
println(jointoString(list, "; ", "(", ")"))
//출력값
result start: (
result end: (1
result start: (1
result end: (1; 2
result start: (1; 2
result end: (1; 2; 3
(1; 2; 3)
}
//joinToString 함수를 직접 구현해보자
fun <T> jointoString(
collection: Collection<T>,
separator: String,
prefix: String,
postfix: String
): String {
val result = StringBuilder(prefix)
for ((index, element) in collection.withIndex()) {
println("result start: ${result}")
if (index > 0) result.append(separator) //첫 원소앞에는 구분자를 붙이면 안된다
result.append(element)
println("result end: ${result}")
}
result.append(postfix)
return result.toString()
}
jointoString(list, "; ", "(", ")") //가독성이 매우 떨어진다.
jointoString(list, separator = " ", prefix = "(", postfix = ")") //인자의 이름을 명시할 수 있다.
자바에서는 일부클래스에서 오버로딩한 메소드가 너무 많아진다는 문제가 있다.
Constructors
Constructor and Description
Thread()
Allocates a new Thread object.
Thread(Runnable target)
Allocates a new Thread object.
Thread(Runnable target, String name)
Allocates a new Thread object.
Thread(String name)
Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target)
Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target, String name)
Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
Thread(ThreadGroup group, String name)
Allocates a new Thread object.
디폴트 파라미터를 설정하여 오버로드 상당수를 피할 수 있다.
fun <T> jointoString(
collection: Collection<T>,
separator: String = ", ",
prefix: String = "",
postfix: String =""
): String {
fun main() {
val list = listOf(1, 2, 3)
println(jointoString(list, "; ", "(", ")"))
println(jointoString(list, prefix = "; ", separator = "(", postfix = ")")) //이름 붙인 인자면 순서 변경해도 상관없다.
println(jointoString(list)) //다 생략
println(jointoString(list, "; ")) //separator만 작성
}
//출력값
(1; 2; 3)
; 1(2(3)
1, 2, 3
1; 2; 3