Kotlin

[Kotlin] - 코틀린 기본 문법 3

팡세영 2022. 7. 9. 10:00

불변형 List 생성하기

fun main(array: Array<String>){
    var numbers: List<Int> = listOf(1,2,3,4,5)
    var names: List<String> = listOf("one","two","three")
    var mixedType = listOf("Hello", 1, 2.45, 's')   // <Any> 타입

    for(number in numbers) print(number)    //  12345
    println()

    for(index in names.indices) println("names[$index] = ${names[index]}")  // names[0] = one

    for (index in names.indices)    // 짝수 요소만
        if(index % 2 == 0) println("names[$index] = ${names[index]}")
}

emptyList()

val emptyList: List<String> = emptyList<String>()

비어있는 List를 생성하려면 emptyList<>()를 사용할 수 있다.

List의 주요 멤버 메서드

멤버 메서드 설명
get(index:Int) 특정 인덱스를 인자로 받아 해당 요소를 반환한다.
indexOf(element:E) 인자로 받은 요소가 첫 번째로 나타나는 인덱스를 반환하며, 없으면 -1을 반환한다.
lastIndexOf(element: E) 인자로 받은 요소가 마지막으로 나타나는 인덱스를 반환하고, 없으면 -1을 반환
listIterator() 목록에 있는 iterator를 반환한다.
subList(fromIndex: Int, toIndex: Int) 특정 인덱스의 from과 to 범위에 있는 요소 목록을 반환한다.

List의 기본 멤버 메소드 사용해보기

fun main(array: Array<String>){
    var names: List<String> = listOf("one", "two","three")

    println(names.size) //  List 크기     3
    println(names.get(0))   //  해당 인덱스의 요소 가져오기     one
    println(names.indexOf("three")) //  해당 요소의 인덱스 가져오기     2
    println(names.contains("two"))  // 포함 여부 확인 후 포함되어 있으면 true 반환      true
}

가변형 List 생성하기

arrayListOf()


fun main(array: Array<String>){
    //  가변형 List를 생성하고 자바의 ArrayList로 반환
    val stringList: ArrayList<String> = arrayListOf<String>("Hello", "Kotlin", "Wow")
    stringList.add("Java")  //  추가
    stringList.remove("Hello")  // 삭제
    println(stringList) //  [Kotlin, Wow, Java]
}

mutableListOf()

fun main(array: Array){  
// 가변형 List의 생성 및 추가, 삭제, 변경  
val mutableList: MutableList = mutableListOf("kildong","Dooly","Chelsu")  
mutableList.add("Ben") // 추가  
mutableList.removeAt(1) // 인덱스 1번 삭제  
mutableList\[0\]="Sean" // 인덱스 0번을 변경, set(index: Int, element: E)와 같은 역할  
println(mutableList) // \[Sean, Chelsu, Ben\]

// 자료형의 혼합
val mutableListMixed = mutableListOf("Android", "Apple",5,6,'X')
println(mutableListMixed) // [Android, Apple, 5, 6, X]


}

 

불변형 List를 가변형으로 변환하기

    val names: List<String> = listOf("one", "two","three")  //  불변형 List 초기화
    val mutableNames = names.toMutableList()    //  새로운 가변형 List가 만들어짐
    mutableNames.add("four")    //  가변형 List에 하나의 요소 추가
    println(mutableNames)   //  [one, two, three, four]

코틀린에서 List는 읽기 전용 컬렉션으로 데이터의 수정이나 삭제가 불가능하다.

따라서, add, remove와 같은 메소드를 사용할 수 없기 때문에 MutableList를 사용해야 데이터 수정이 가능해진다