팡세영
Log sey
팡세영
전체 방문자
오늘
어제
  • 분류 전체보기 (73)
    • PS (45)
      • programmers (13)
      • 백준 (29)
    • Android (16)
    • Daily (0)
    • Kotlin (6)
    • Design Pattern (1)
    • Java (1)
    • Flutter (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • BFS
  • binding
  • 해쉬맵
  • programmers
  • 구현
  • 정렬
  • 완전탐색
  • compose
  • mvvm
  • 안드로이드
  • 골드
  • LEVEL2
  • 실버
  • java
  • 프로그래머스
  • flutter
  • 하단네비게이션바
  • TestCode
  • ArcitecturePattern
  • 백준
  • 문자열
  • CustomView
  • Android
  • programmers #프로그래머스
  • Kotlin
  • 코틀린
  • DFS
  • 자바
  • 이분탐색
  • 의존성 주입

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
팡세영

Log sey

[Kotlin] - 코틀린 기본 문법 3
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를 사용해야 데이터 수정이 가능해진다

'Kotlin' 카테고리의 다른 글

Android Kotlin - DIP(Dependency Inversion Principle)이란?  (0) 2023.07.14
Android - Kotlin으로 RecyclerView 구현하기  (0) 2022.07.29
[Kotlin] - 코틀린 기본 문법 4  (0) 2022.07.10
[Kotlin] - 코틀린 기본 문법 2  (0) 2022.07.08
[Kotlin] - 코틀린 기본 문법 1  (0) 2022.07.08
    'Kotlin' 카테고리의 다른 글
    • Android - Kotlin으로 RecyclerView 구현하기
    • [Kotlin] - 코틀린 기본 문법 4
    • [Kotlin] - 코틀린 기본 문법 2
    • [Kotlin] - 코틀린 기본 문법 1
    팡세영
    팡세영
    Android, CS, PS

    티스토리툴바