2012-11-27 5 views

답변

2

예, 용량은 그대로 유지됩니다. (적어도이 아닌 오라클 VM의 구현에) :

/** 
* Removes all of the elements from this list. The list will 
* be empty after this call returns. 
*/ 
public void clear() { 
    modCount++; 

    // Let gc do its work 
    for (int i = 0; i < size; i++) 
     elementData[i] = null; 

    size = 0; 
} 

그냥 명확하게하기 : ArrayList는 배열에 연동 (예 : INT [] ArrayList를위한) 당신이 가서 때마다 해당 배열이 확장됩니다 용량을 늘리려면 새로운 어레이를 만들고이를 복사해야합니다. 정리 (코드에서 볼 수 있듯이)는 더 작은 새로운 배열을 만들고 거기에 복사하고 이전의 큰 배열을 파괴하지 않습니다.

1

아니요, 목록에서 요소를 제거하면 arrayList의 용량이 변경되지 않습니다. 그러나 당신은 trimToSize을 사용하여 스스로 할 수 있습니다.

일반적으로 더 많은 요소를 추가 할 때 용량이 증가함에 따라 용량에 대해 걱정할 필요가 없습니다. 용량에 대해 걱정할 수있는 이유는 빈번한 재 할당으로 인한 성능입니다. 그렇지 않으면 용량을 다시 초기화하는 것에 대해 걱정할 필요가 없습니다.

1

Capacity of ArrayList의 도움으로 용량이 재설정되지 않을 수 있습니다. 샘플 코드 찾기 :

import java.lang.reflect.Field; 
import java.util.ArrayList; 
public class Main { 

    public static void main(String[] args) { 
     try { 
      ArrayList<Object> al = new ArrayList<Object>(500); 
      System.out.println(getCapacity(al)); 
      for (int i = 0; i < 550; i++) { 
       al.add(new Object()); 
      } 
      System.out.println(getCapacity(al)); 
      al.clear(); 
      System.out.println(getCapacity(al)); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 

    static int getCapacity(ArrayList<?> l) throws Exception { 
     Field dataField = ArrayList.class.getDeclaredField("elementData"); 
     dataField.setAccessible(true); 
     return ((Object[]) dataField.get(l)).length; 
    } 
} 
관련 문제