2013-06-07 5 views
27

ArrayList에서 마지막 객체를 신속하게 제거하고 싶습니다.Java에서 ArrayList의 마지막 객체 제거

나는 remove(Object O)ArrayListO(n) 걸리는 것을 알고 있지만, 나는 내가 단지 마지막 개체를 제거 할 이후 일정 시간이 작업을 수행 할 수 궁금해?

+0

또한'가 제거된다 (INT)'... –

+18

'list.remove (는 list.size() - 1)'! – NINCOMPOOP

+2

스택이 더 나은 해결책이 될까요? –

답변

52

의 구문은 다음과 같이 the documentation for ArrayList#remove(int)를 참조하십시오

여기
list.remove(list.size() - 1) 

가 구현 어떻게입니다. elementData은 배킹 배열을 찾아 (배열에서 느슨하게 잘라낼 수 있습니다.) 일정 시간이어야합니다 (JVM이 객체 참조의 크기와 오프셋을 계산할 수있는 항목의 수를 알고 있기 때문에) numMoved 이 경우에 0입니다 :

public E remove(int index) { 
    rangeCheck(index); // throws an exception if out of bounds 

    modCount++;  // each time a structural change happens 
         // used for ConcurrentModificationExceptions 

    E oldValue = elementData(index); 

    int numMoved = size - index - 1; 
    if (numMoved > 0) 
     System.arraycopy(elementData, index+1, elementData, index, 
         numMoved); 
    elementData[--size] = null; // Let gc do its work 

    return oldValue; 
} 
관련 문제