• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

java ArrayList의 동작

20 May 2024

Reading time ~2 minutes

java ArrayList의 동작

테스트용 코드 전체

import java.lang.reflect.Field

fun main() {
//    val list = MutableList<String?>(1000) { null } // 초기 크기 설정
    val list = mutableListOf<Int>()
    println("list size : ${list.size} / list capacity:: ${getCapacity(list)}") // # 1 초기 생성
    for ( i in 0..25) {
        list.add(i+1)
        println("list size : ${list.size} / list capacity:: ${getCapacity(list)}") // # 2 출력
    }
}
// arraylist의 capacity 출력 
fun getCapacity(arrayList: List<*>?): Int {
    if (arrayList == null) {
        return 0
    }
    val field: Field = ArrayList::class.java.getDeclaredField("elementData")
    field.isAccessible = true

    return (field.get(arrayList) as Array<*>).size
}

결과 값

list size : 0 / list capacity:: 0 // #1
list size : 1 / list capacity:: 10 // capacity 변화
list size : 2 / list capacity:: 10
list size : 3 / list capacity:: 10
list size : 4 / list capacity:: 10
list size : 5 / list capacity:: 10
list size : 6 / list capacity:: 10
list size : 7 / list capacity:: 10
list size : 8 / list capacity:: 10
list size : 9 / list capacity:: 10
list size : 10 / list capacity:: 10
list size : 11 / list capacity:: 15 // capacity 변화
list size : 12 / list capacity:: 15
list size : 13 / list capacity:: 15
list size : 14 / list capacity:: 15
list size : 15 / list capacity:: 15
list size : 16 / list capacity:: 22 // capacity 변화
list size : 17 / list capacity:: 22
list size : 18 / list capacity:: 22
list size : 19 / list capacity:: 22
list size : 20 / list capacity:: 22
list size : 21 / list capacity:: 22
list size : 22 / list capacity:: 22
list size : 23 / list capacity:: 33 // capacity 변화
list size : 24 / list capacity:: 33
list size : 25 / list capacity:: 33
list size : 26 / list capacity:: 33

설명

ArrayList는 List 인터페이스를 구현한 동적 배열입니다. 내부적으로는 배열을 사용하여 요소를 저장하며, 필요에 따라 크기를 조절할 수 있습니다.

  • 최초에 리스트를 생성하면, 크기와 용량 모두 0입니다.
  • 요소를 추가할 때마다 용량이 증가합니다. 용량이 모두 차면 새로운 배열을 생성하고 기존 데이터를 복사합니다.

동작 예시

  • 최초 list를 생성하고, size와 capacity를 확인하면 0 / 0
  • list에 처음 데이터를 add 할 경우, size / capacity 는 1 / 10
  • list에 2번째 데이터를 add
  • list에 10번째 데이터를 add
  • list에 11번째 데이터를 add 하면 새로운 배열을 생성하고, 기존 데이터를 아래와 같이 복사

참고 자료

  • The Capacity of an ArrayList vs the Size of an Array in Java
  • Ehcache에서 만난 warning ‘The JVM is preventing Ehcache from accessing the subgraph beneath ~ cache sizes may be underestimated as a result’
  • ArrayList
  • [Java] ArrayList는 어떻게 동적으로 사이즈가 늘어나는가? add() flow(동작 방식)


arraylistjava Share Tweet +1