2012-03-18 2 views
3

정확한 크기를 알고있는 ArrayList 객체가 있습니다. ArrayList의 용량을 확장해서는 안됨을 지정하는 방법이 있습니까?ArrayList 크기 조정

List<String> list = null; 
int size = getSize(); // gets the exact number of elements I want 

list = new ArrayList<String> (size); 

for (int i = 0; i < size; i++) { 
    list.add("String num: " + i); 
} 

시간 낭비를 피하기 위해 ArrayList의 크기를 조정하지 않으려합니다.

답변

14
list = new ArrayList<String> (size); 

이렇게하면 초기 용량으로 '크기'를 가진 arraylist가 생성됩니다. '크기'보다 많은 요소를 추가하지 않는 한 크기를 조정할 수 없습니다.

또한 애플리케이션에 실제로 시간이 걸릴 수도 있습니다. 이 문제를 프로파일 링하고 확인하지 않으면 코드를 무작위로 최적화하여 많은 것을 얻을 수 없습니다.

+1

ArrayList 실제로 크기를 조정하는 데 오래 걸립니까? 나는 그것이 매우 빠른 조작이고 아무도 괴롭히지 않아야한다고 생각한다. – vach

5

용량이 초과 된 요소를 추가하지 않으면 ArrayList의 크기가 조정되지 않습니다. 적절한 용량의 목록을 만들었으므로 괜찮습니다.

원래 용량을 초과하려고 시도했을 때 예외가 발생하는 목록을 만들지 만, 여기가 왜 유용했는지는 명확하지 않습니다.

+2

마찬가지로 추가 정보로 ['ensureCapacity (int minCapacity)'] (http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList)를 사용하여 임의로 크기를 조정할 수 있습니다. html # ensureCapacity % 28int % 29) 메소드를 사용하십시오. –

2

정확한 크기를 알고 있고 앞으로 확장되지 않으면 왜 문자열 배열을 사용하지 않는가?

String[] strArray=new String[size]; 
+0

나는 ArrayList에 대해 다른 타입을 사용하고 있는데, 지금은 그것에 들어가기를 원치 않는다. ArrayList 인터페이스가 간단한 Object 배열을 사용하는 것보다 낫습니다. –

1

당신은 ArrayList 다음 샘플과 같은 ensureCapacity(int minCapacity) 메소드를 오버라이드 (override)하는 것입니다 제한 할 수있는 무엇 :

작은 테스트는 다음 코드와 함께 할 수
public static class MyArrayList<T> extends ArrayList<T> { 

    @Override 
    public void ensureCapacity(int minCapacity) { 
     if (minCapacity > 10) { 
      throw new IllegalArgumentException(); 
     } 
     super.ensureCapacity(minCapacity); 
    } 

} 

:

public static void main(String[] args) { 
    MyArrayList<String> items = new MyArrayList<String>(); 

    for (int i = 0; i < 15; i++) { 
     try { 
      items.add("itm " + i); 
      System.out.println("succeeded to insert " + i); 
     } catch (IllegalArgumentException e) { 
      System.out.println("not able to insert " + i); 
     } 
    } 

    System.out.println("items are: " + items); 
} 

다음과 같이 인쇄됩니다.

succeeded to insert 0 
succeeded to insert 1 
succeeded to insert 2 
succeeded to insert 3 
succeeded to insert 4 
succeeded to insert 5 
succeeded to insert 6 
succeeded to insert 7 
succeeded to insert 8 
succeeded to insert 9 
not able to insert 10 
not able to insert 11 
not able to insert 12 
not able to insert 13 
not able to insert 14 
items are: [itm 0, itm 1, itm 2, itm 3, itm 4, itm 5, itm 6, itm 7, itm 8, itm 9] 
관련 문제