TIL) JAVA - ArrayList

oatraspberry·2022년 12월 18일
post-thumbnail

ArrayList

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

public class ~~ {
	public static void main(String[] args) {
    	String[] arrayObj = new String[2];
        arrayObj[0] = "one";
        arrayObj[1] = "two";
        // arrayObj[2] = "three"; // 오류 발생
        for ( int i = 0 ; i < arrayObj.length; i++) {
        System.out.println(arrayObj[i]);
    }
    
    ArrayList al = new ArrayList();
    al.add("one"); // = (arrayObj[0] = "one";)
    al.add("two"); 
    al.add("three");
    for (int i = 0; i < al.size(); i++) {
    	System.out.println(al.get(i));
    }
}

ArrayList의 메서드

생성자

  • ArrayList() - 기본 생성자
  • ArrayList(Collection c) - 매개변수를 Collection으로 주면 그 Collection에 저장돼있는 ArrayList를 만들 수 있음.
  • ArrayList(int initialCapacity - 배열의 길이

추가

  • boolean add(Object o) - 성공: true, 실패: false
  • void add(int index Object element) - index 어디에 저장할지 저장위치 정할 수 있다.
  • boolean addAll(Collection c) - Collection이 가진 요소 그대로 저장.
  • boolean addAll(int index, Collection c) - index 어디에 저장할지 저장위치 정할 수 있다.

삭제

  • boolean remove(Object o)
  • Object remove(int index) - 특정 위치 삭제
  • boolean removeAll(Collection c) - Collection이 가진 객체 삭제.
  • void clear() - 모든 객체 삭제.

검색

  • int indexOf(Object o) - 왼쪽에서 오른쪽으로 객체를 찾음. 객체가 못 찾으면 -1 반환.

  • int lastIndexOf(Object o) - 오른쪽에서 왼쪽으로 객체를 찾음.

  • boolean contains(Object o) - 객체가 존재하는지 있으면 true, 없으면 false.

  • Object get(int index) - 특정 위치 객체 읽기.

  • Object set(int index, Object element) - set은 특정 위치에 있는 객체 변경.

  • List subList(int fromIndex, int toIndex) - 리스트에서 일부만 뽑아내서 새로운 list 만드는 것.

  • Object[] toArray() - ArrayList가 가지고 있는 객체 배열 반환.

  • Object[] toArray(Object[] a)

  • boolean isEmpty() - ArrayList가 비어있는지 확인.

  • void trimToSize() - 빈 공간 제거.

  • int size() - ArrayList에 저장된 객체의 갯수 확인.

출처 - 자바의 정석

profile
개발자가 될테야

0개의 댓글