Nuke Olaf - Log Store

[Kotlin] 안드로이드 - ArrayList 와 mutableListOf 의 차이 본문

Language/[Kotlin]

[Kotlin] 안드로이드 - ArrayList 와 mutableListOf 의 차이

NukeOlaf 2020. 4. 10. 14:40

ArrayList 와 mutableListOf 의 차이

val a = mutableListOf<String>()

val b = ArrayList<String>()

 

Kotlin 공홈에 가보면, ArrayList 는 MutableList 인터페이스를 상속받은 구현체임을 알 수 있다.

class ArrayList<E> : MutableList<E>, RandomAccess

명시적으로 처음부터 MutableList 중 특별히 ArrayList 를 원하는 경우에는 ArrayList 로 선언하고,
List 이지만 수정, 삭제가 가능한(Mutable) 한 리스트를 원하는 경우에는 List 로 선언하는 것이 좋다고 한다.

어차피 Compile Time 에는 ArrayList 든 MutableList 든 List 로 인식되므로 큰 차이는 없다고 함.

 

The only difference between the two is communicating your intent.

When you write val a = mutableListOf(), you're saying "I want a mutable list, and I don't particularly care about the implementation". When you write, instead, val a = ArrayList(), you're saying "I specifically want an ArrayList".

In practice, in the current implementation of Kotlin compiling to the JVM, calling mutableListOf will produce an ArrayList, and there's no difference in behaviour: once the list is built, everything will behave the same.

Now, let's say that a future version of Kotlin changes mutableListOf to return a different type of list.

Likelier than not, the Kotlin team would only make that change if they figure the new implementation works better for most use cases. mutableListOf would then have you using that new list implementation transparently, and you'd get that better behaviour for free. Go with mutableListOf if that sounds like your case.

On the other hand, maybe you spent a bunch of time thinking about your problem, and figured that ArrayList really is the best fit for your problem, and you don't want to risk getting moved to something sub-optimal. Then you probably want to either use ArrayList directly, or use the arrayListOf factory function (an ArrayList-specific analogue to mutableListOf).

 

코틀린 공홈 mutableList >>>

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/

코틀린 공홈 arrayList >>>

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/

스택오버 플로우 >>>

https://stackoverflow.com/questions/53218501/using-kotlins-mutablelist-or-arraylist-where-lists-are-needed-in-android

https://stackoverflow.com/questions/43114367/difference-between-arrayliststring-and-mutablelistofstring-in-kotlin

 

참고 사이트 >>>

https://zladnrms.tistory.com/140

https://namget.tistory.com/entry/%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C%EB%82%98%EC%9D%B4%EC%B8%A0-%EB%B1%85%ED%81%AC%EC%83%90%EB%9F%AC%EB%93%9C-%EC%BD%94%ED%8B%80%EB%A6%B0%EB%8D%98%EC%A0%84-2-3%EB%B2%88%EB%AC%B8%EC%A0%9C

 

Comments