ArrayList

iy·2024년 1월 9일
0

Java-CollectionFramework

목록 보기
2/7

ArrayList

  • ArrayList는 기존의 Vector를 개선한 것으로 구현원리와 기능적으로 동일
    • ArrayList와 달리 Vector는 자체적으로 동기화처리가 되어 있음
  • List 인터페이스를 구현하므로, 저장순서가 유지되고 중복을 허용
  • 데이터의 저장공간으로 배열을 사용(배열 기반)

ArrayList 메서드

  • 생성자
ArrayList()
ArrayList(Collection c)
ArrayList(int initialCapacity)
  • 추가
boolean add(Object o) 
void add(int index, Object element)
boolean addAll(Collection c)
boolean addAll(int index, Collection c)
  • 삭제
boolean remove(Object o)
Object remove(int index)
boolean removeAll(Collection c)
void clear()
  • 검색
int indexOf(Object o)
int lastIndexOf(Object o)
boolean contains(Object o)
Object get(int index)
Object set(int index, Object element)
  • 그 외
List subList(int fromindex, int toindex) // 배열의 원하는 부분 새롭게 리스트로 만듬
Object[] toArray() // ArrayList의 객체 배열을 반환
Object[] toArray(Object[] a)
boolean isEmpty() // 비어있는지 확인
void trimToSize() // 빈 공간 제거
void size() // 저장된 객체 갯수 반환

ArrayList에 저장된 객체의 삭제 과정

  • ArrayList에 저장된 세번째 데이터(data[2])를 삭제하는 과정
list.remove(2); 

를 호출

  1. 삭제할 데이터 아래의 데이터를 한 칸씩 위로 복사해서 삭제할 데이터를 덮어씀
System.aaraycopy(data, 3, data, 2,2); // data[3]에서 data[2]로 2개의 데이터를 복사하라는 의미
  1. 데이터가 모두 한 칸씩 이동했으므로 마지막 데이터는 null로 변경
data[size-1] = null;
  1. 데이터가 삭제되어 데이터의 갯수가 줄었으므로 size의 값을 감소시킴
size--;

마지막 데이터를 삭제하는 경우 1의 과정(배열 복사)는 필요하지 않다!

배열 복사가 발생하는 경우와 그렇지 않은 경우

  1. ArrayList에 저장된 첫 번째 객체부터 삭제하는 경우 : 배열 복사 발생
for(int i =0;i <list.size();i++){
    list.remove(i);
}
  • 배열복사에 의해 남는 값들이 발생
  1. ArrayList에 저장된 마지막 객체부터 삭제하는 경우 : 배열 복사 발생 안함
for(int i = list.size()-1;i>=0;i--){
    list.remove(i);
}
  • 계속 마지막 객체를 삭제하므로 다 지워짐(속도도 더 빠름)

☃참고❄
자바의 정석- ArrayList

0개의 댓글