[Kotlin] List

dnjstjt12·2024년 6월 26일

Collection

Collection 타입에는 List, Set, Map이 있다.

Collection은 read-only 동작을 나타낸다.
MutableCollection은 read-write 동작을 나타낸다.

  • Collection<T>는 Collection의 최상위 계층으로, Collection 원소 개수를 세거나, 특정 원소를 확인하는 기능이 있다.
  • Collection<T>는 Iterable<T>를 상속받아 사용한다.
    Iterable<T>안의 iterator()함수는 Iterator<T>를 overload했다.
  • mutableCollecion<T>는 add()와 remove()등의 함수를 추가해 write할 수 있다.

Iterator

iterator는 컬렉션에 저장되어 있는 값을 순차적으로 순회하기 위한 수단으로, iterator()함수 호출로 동작이 이루어진다.

ListIterator<T>는 Iterator<T>를 상속받아 List의 순회를 담당한다.

  • 순방향과 양방향 List itorator를 제공한다.

MutableListIterator<T>는 Iterator<T>와 ListIterator<T>를 상속 받아 mutable List 순회를 담당한다.

  • ListIterator와 차이는 set(),add(),remove()함수를 통해 List의 Element를 write할 수 있다.

List vs MutableList

List는 Collection<T>를 상속받은 Collection 종류 중 하나다.
read-only이다. 즉 수정이 불가능한 List다.

MutableList는 MutableCollection<T>를 상속받은 MutableCollection 종류 중 하나다.
read-write이다. 삭제, 삽입, 수정 모두 가능하다.

다음은 List를 선언하는 방법이다.

val A: List<Type> = List(size, {value})
val B: MutableList<Type> = MutableList(size, {value})
val A: List<Type> = listOf(value1, value2, value3, value4 ...)
val B: MutableList<Type> = MutablelistOf(value1, value2, value3, value4 ...)

List는 listIterator()를 통해 ListIterator<T> 사용할 수 있고,
MutableList는 MutableListIterator()를 통해 MutbaleListIterator<T> 사용할 수 있다.

List<T>

리스트가 무엇인지 알았으니, List<T>의 사용법을 알아보자.

  1. size
val A: List<Int> = List(5, {0})
A.size

list의 크기를 알려주는 변수다.

  1. isEmpty()
val list: List<Int> = List(5, {0})
A.isEmpty()  //false

빈 list 여부를 알려준다.

  1. contains()
val A: List<Int> = listOf(4,3,2,4)
A.contains(4)  //true

지정된 Element가 List에 있는지 알려준다.

  1. containsAll()
val A: List<Int> = listOf(4,3,2,4)
val B = A.containsAll()(listOf<Int>(4,3))  //true

지정된 Element들이 list에 모두 들어있는지 여부를 확인해준다.

  1. get()
val A: List<Int> = listOf(4,3,2,4)
val B = A.get(0) // 4

지정된 index를 통해 해당 Element를 찾아준다.

  1. subList()
val A: List<Int> = listOf(4,3,2,4)
val B = A.subList(0,1) // (4,3)

List를 잘라준다.

MutableList<T>

MutableList<T>는 List<T>를 상속받아 List의 기능을 수행한다.
추가로 add,remove,set의 기능을 하여 list를 write할 수 있다.

  1. add()
val A: mutableList<Int> = mutableListOf(4,3,2,4)
val B = A.add(1) // (4,3,2,4,1)

지정된 element를 추가한다.

val A: mutableList<Int> = mutableListOf(4,3,2,4)
val B = A.add(1,5) // (4,5,3,2,4)

지정된 index에 element를 추가한다.

  1. remove()
val A: mutableList<Int> = mutableListOf(4,3,2,4)
val B = A.remove(1) // (3,2,4)

지정된 element를 제거한다.

  1. set()
val A: mutableList<Int> = mutableListOf(4,3,2,4)
val B = A.set(1,5) // (4,5,2,4)

지정된 index의 element를 수정한다.

ArrayList vs Array

Array는 삭제와 삽입은 불가능하고, 수정만 가능하다. Collection의 종류는 아니다.

ArrayList는 MutableList의 종류로 Array와는 다르다.

profile
안녕하세요!

0개의 댓글