본문 바로가기
💡 Kotlin

[Kotlin] mutable Collection

by 콩드로이드 2023. 1. 8.

2023.01.03 - [💡 Kotlin] - [Kotlin] Collection (List, Set, Map)

 

[Kotlin] Collection (List, Set, Map)

많이 접한만큼 익숙한 자료구조이지만, 한번 더 살펴보겠습니다 Collection 자료구조 중 하나로, 크게 3가지 컬렉션이 있습니다 (List, Set, Map) List와 Set은 Collection을 상속받고, Map은 독자적입니다 간

kong-droid.com

 

이전 포스팅에서 Collection에 대해 알아봤는데, 

Collection 인터페이스에서 원소를 수정하려면 Mutable Collection을 사용해야해요 

오늘은 Mutable Collection에 대해 알아보겠습니다 ✏️

 


MutableCollection

interface MutableCollection<E>: Collection<E>, MutableIterable<E>

 

Collection과 MutableIterable을 상속하고 있는 형태입니다 

 

MutableIterable은 아래와 같이 선언되어있습니다 

interface MutableIterable<out T>: Iterable<T>
{
  override fun iterator() : MutableIterator<T>
}

 

바로 원소를 수정할 수 있게끔 멤버를 가지고 있는 인터페이스가 MutableIterable<E>에요 

 

 

MutableIterable의 멤버

 

원소 추가

각각 원소를 추가했으면 true, 원소를 추가하지 못하면 false를 반환

abstract fun add(element:E): Boolean
abstract fun addAll(elements: Collection<E>): Boolean

 

 

 

원소 삭제

abstract fun remove(element: E): Boolean
abstract fun removeAll(elements: Collection<E>): Boolean
abstract fun retainAll(elements: Collection<E>): Boolean
abstract fun clear()

• remove : if(element 성공적으로 제거) true else false

 removeAll : if(elements원소들과 일치하는 모든 원소를 제거 , 하나라도 제거되면) true else false

retainAll : elements와 일치하는 원소만 남기고 컬렉션에서 모두 제거, 하나라도 제거되면 true 삭제된 원소가 없으면 false

clear : Collection의 모든 원소 삭제 

 

 


MutableIterator 

커서가 가리키고 있는 원소를 삭제할 수 있는 인터페이스

public interface MutableIterator<out T>: Iterator<T>
{
   public fun remove(): Unit
}

 

next로 다음 커서로 이동 후 remove로 삭제

val list = mutableListOf(1,2,3)
val iterator : MutableIterator<Int> = list.iterator()

iterator.next()
iterator.remove()

println(list)

 

출력값은 2,3이 된다 🥹

 

 

 


MutableIist

MutableList<E>는 MutableCollection<E>를 상속하고, MutableList<E>에 추가된 멤버들은

abstract fun add(index:Int, element:E): Unit
abstract fun addAll(index:Int, elements:Collection<E>): Boolean
abstract operator fun set(index:Int, element: E):E
abstract fun removeAt(index: Int): E

 

add : index위치에 element 추가

addAll : index 위치에 elements 모두 추가 , List에 변경이 생겼으면 true

set : []를 오버로딩하는 연산자로 index번째의 원소를 element로 교체, 이 때 반환값은 이전 index위치에 있던 원소

removeAt : index번째 원소를 삭제하고 삭제된 원소를 반환

 

val list: MutableList<Char> = mutableListOf('c', 'a', 'r')
println(list.set(2, 'T')
println(list)

 

결과값

더보기

r

[c,a,T]

 

 


MutableListIterator

ListIterator<T>, MutableIterator<T>를 구현

MutableListIterator에 추가된 멤버

 

 

원소교체

 커서가 가르키는 위치의 원소를 element로 교체

abstract fun set(element: T): Unit

 

 

 

원소추가

abstract fun add(element:T): Unit

 


 

MutableSet은 MutableColletion을 상속하고, 따로 추가된 멤버가 없다 :)

 

⭐️ MutableMap

Map<K, V>를 상속

interface MutableEntry<K, V>: Map.Entry<K, V>
{
  fun setValue(new Value: V): V
}

setValue시 반환값은 이전에 갖고 있던 값이다 

 

 

MutableMap의 프로퍼티

override val keys: MutableSet<K>
override val values: MutableCollection<V>
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>

keys는 중복이 불가능 하니까 Set으로 선언 ☺️

 

 

MutableMap의 함수

 

put

abstract fun put(key: K, value: V): V?

 • 키-값을 추가하고 null 반환

• 이미 동일한 key가 존재하면, value를 교체하고 이전에 갖고있던 value를 반환

 

 

remove(K)

abstract fun remove(key: K): V?

• if(key와 연관된 value 존재) value 삭제 후 return value else return null

 

 

 

remove(K,V)

abstract fun remove(key: K, value: V): Boolean

• if(key-value 일치하는 쌍이 있으면) 쌍 삭제  return true else return false

 

 

 

putAll(Map<K,V>)

abstract fun putAll(from : Map<out K, V>): Unit

• from에 있는 키-값 모두 추가, 만약 키가 이미 존재하면, value만 변경 

 

 

clear

abstract fun clear(): Unit

• 모든 키-값 삭제