import java.util.ArrayList;
array를 private 필드로 가지고 있음 + 꽉 찰때마다 더 긴 array가 생성되어 이동
ArrayList<T> aList = new ArrayList<T>(); //초기는 capacity 10
ArrayList<String> bList = new ArrayList<String>(20)
ArrayList 객체는 array보다 비효율적ArrayList의 요소는 class type이어야 함. primitive type은 불가능사용자 정의 클래스 타입
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 30));
list.add(new Person("Bob", 25));
System.out.println(list);
list.add(1, new Person("Charlie", 35));
System.out.println(list);
Person p = list.get(1);
System.out.println(p);
list.set(1, new Person("David", 40));
System.out.println(list);
list.remove(2);
System.out.println(list);
list.remove(new Person("Alice", 30));
System.out.println(list);
ArrayList의 상위 클래스인 AbstractList클래스에서 protected메소드로 정의되어 있음
따라서 ArrayList를 상속받은 커스텀클래스를 통해 removeRange를 사용해야 함
import java.util.ArrayList;
class CustomArrayList<E> extends ArrayList<E> {
@Override
protected void removeRange(int fromIndex, int toIndex) {
super.removeRange(fromIndex, toIndex);
}
}
public class Main {
public static void main(String[] args) {
CustomArrayList<Person> list = new CustomArrayList<>();
list.add(new Person("Alice", 30));
list.add(new Person("Bob", 25));
list.add(new Person("Charlie", 35));
list.add(new Person("David", 40));
list.add(new Person("Eve", 22));
System.out.println("Before removeRange: " + list);
list.removeRange(1, 4);
System.out.println("After removeRange: " + list);
}
}
list.clear();
System.out.println(list);
boolean contains = list.contains(new Person("Alice", 30));
System.out.println(contains);
int index = list.indexOf(new Person("Alice", 30));
System.out.println(index);
int lastIndex = list.lastIndexOf(new Person("Alice", 30));
System.out.println(lastIndex);
최소 용량 보장
리스트의 용량을 현재 크기로 줄임
Object[] array = list.toArray();
for (Object obj : array) {
System.out.println(obj);
}
지정된 배열에 리스트의 모든 요소를 포함시킴
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 30));
list.add(new Person("Bob", 25));
list.add(new Person("Charlie", 35));
list.add(new Person("David", 40));
list.add(new Person("Eve", 22));
System.out.println("Original list: " + list);
// Person 배열로 변환
Person[] personArray = list.toArray(new Person[0]);
for (Person p : personArray) {
System.out.println(p);
}
}
}
인자로 전달된 배열이 list보다 작은경우 새 배열을 만들어 전달.
얕은복사!!
ArrayList<Person> clonedList = (ArrayList<Person>) list.clone();
System.out.println(clonedList);