brograming
[Collection] ArrayList 본문
ArrayList
ㆍList 인터페이스를 구현하므로, 순서 o, 중복o
ㆍ데이터의 저장공간으로 배열을 사용한다. (배열 기반)
ㆍ길이와 타입(제너릭)의 제약이 없음
ㆍArrayList는 객체를 담는다.
생성자 : ArrayList() 기본 생성자 , ArrayList(Collection c) 매개변수 , ArrayList(int initialCapacity) initialCapacity : 배열이 길이
추가 : list.add(Object o), list.add(int index, Object element), list.addAll(Collection c), list.addAll(int index, Collection c)
검색 : list.indexof(Object o), list.lastindexof(Object o)
읽기 : list.get(int index)
변경 : list.set(int index, Object element)
ArrayList list = new ArrayList();
//add(); 끝에 데이터 추가
list.add("asdf"); // String
list.add(1); // int
list.add(3.45f); // float
list.add(23.45); // double
System.out.println("데이터 개수 : " + list.size());
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
ArrayList 생성
ArrayList는 생성할 때 크기를 지정하거나 지정하지 않고 만들 수 있다.
크기를 지정해서 생성할 때 저장할 개수보다 약간 여유있는 크기로 만든다. 지정한 크기보다 더 많은 객체를 저장하면 자동적으로 크기가 늘어나지만 이 과정에서 처리시간이 많이 소요된다.
new ArrayList(); / new ArrayList(10);
list.add()
ArrayList는 객체 를 담는다. object[] 배열이기 때문에 기본형을 담을 수 없다.
아래의 예제처럼 list.add(1); int 1를 담는 것 처럼 보이지만 실제로는 autoboxing에 이 의해 기본형이 참조형으로 자동 변환되어
list.add(new integer(1))로 객체가 담기는 것이다. add()로 마지막 데이터 다음 위치에 저장된다.
list.add("asdf");
list.add(1); // list.add(new integer(1));
list.add(3.45f);
list.add(23.45);
list.size()
ArrayLIst에 들어간 데이터 개수이다. ArrayList를 생성할 때 지정한 크기가 아닌 list에 저장한 데이터 개수이다.
System.out.println("데이터 개수 : " + list.size());
list.get()
list.get(int index) 지정된 위치(index)에 저장된 객체를 반환한다.
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i)); // get(i) : i번째 방의 값 반환
}
list.remove()
list.remove(1); : 인덱스가 1인 데이터 삭제
list.remove(new Integer(1)); : 데이터가 1인 데이터 삭제
list.remove(1);
list.remove(new Integer(1));
ArrayList에 저장된 객체의 삭제 과정
ArrayLIst에 저장된 첫 번째 객체부터 삭제하는 경우(배열 복사 발생)
배열 복사 발생되어 ArrayList내 모든 데이터 삭제불가하다.
for(int i=0; i<list.size(); i++){
list.remove(i);
}
ArrayLIst에 저장된 마지막 객체부터 삭제하는 경우(배열 복사 발생 안함)
배열의 모든 데이터를 삭제할 수 있다. 속도가 빠르다.
for(int i=list.size()-1; i>=0; i--){
list.remove(i);
}'[JAVA]' 카테고리의 다른 글
| 자바 jdk-17 설치 및 환경변수 설정 (0) | 2023.07.25 |
|---|---|
| char 배열을 문자열로 변환 String.valueOf() / new String() (0) | 2023.04.17 |
| [입출력] 바이트 기반 스트림 (0) | 2023.04.17 |
| [입출력] 문자 기반 스트림 (0) | 2023.04.17 |
| [Collection] Map (0) | 2023.04.16 |