List 인터페이스를 상속받은 여러 클래스 중 하나이며 연속되는 메모리 공간을 사용한다.
배열은 크기가 고정되어 있지만 ArrayList는 가변적으로 변한다. 저장 가능한 메모리 용량이 있고 사용 중인 공간이 있다.
만약 가용량보다 큰 값을 메모리에 저장하려고 하면 더 큰 메모리 공간을 할당한다.
import java.util.ArrayList;
ArrayList 클래스를 인포트 해준다.
ArrayList<Integer> int1 = new ArrayList<Integer>(); // 타입 지정
ArrayList<Integer> int2 = new ArrayList<>(); // 타입 생략
ArrayList<Integer> int3 = new ArrayList<>(10); // 초기 용략 설정
ArrayList<Integer> int4 = new ArrayList<>(int1); // 다른 컬랙션으로 초기화
ArrayList<Integer> int5 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); //Arrays.asList()
먼저 타입을 설정을 하거나 안 할 수도 있으며 초기 용량을 설정할 수도 있다. 다른 ArrayList을 전달하면 해당 컬렉션 값으로 초기화가 가능하다. 또한 Arrays.asList(); 를 사용해 기본 값을 생성할 수 있다.
import java.util.ArrayList;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
// 값을 추가 add() Method
colors.add("green");
colors.add("red");
colors.add("blue");
colors.add(0, "yellow");
colors.add("black");
// 값을 변경 set() Method
colors.set(1, "purple");
System.out.println(colors);
}
}
add()을 통해 "colors"에 값이 순차적으로 저장이 된다. 별도로 인덱스를 설정할 경우 해당 인덱스에 값이 저장되고 추가가 된 인덱스부터의 값들이 한 칸씩 밀린다. 또한 set()을 통해 값을 변경할 수 있다.
처음에는 green, red, blue 로 순차적으로 저장이 되고
colors.add(0, "yellow")
을 하게 되면 인덱스 0번인 green을 밀어내고 인덱스 0번에 yellow가 들어간다.
yellow, green, red, blue
위 처럼 나올게 될 것이다.
그리고 colors.set(1, "purple")
처럼 set()를 사용해 인덱스 1번에 있는 green 을 purple로 변경할 수 있다.
colors를 출력하게 되면
yellow, purple, red, blue
이와 같이 출력이 될 것이다.
import java.util.ArrayList;
import java.util.Arrays;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
String removedColor = colors.remove(0);
System.out.println("Removed color : " + removedColor);
color.remove("white");
System.out.println(colors);
colors.clear();
System.out.println(colors);
}
}
ArrayList에서 값을 삭제 할 때는 remove()을 통해 하면 된다. 인덱스를 통해 삭제도 가능하며 값을 직접 줘서 삭제 할 수도 있다.
만약 ArrayList 모든 값을 삭제하고 싶으면 clear()을 사용하면 된다.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
// for-each loop
for(String color : colors) {
System.out.print(color + " ");
}
System.out.println();
// for loop
for(int i = 0; i < colors.size(); ++i) {
System.out.print(colros.get(i) + " ");
}
System.out.println();
// Iterator
Iterator<String> iterator = colors.iterator();
while(iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
// ListIterator
ListIteragtor<String> listIterator = colors.listIterator(colors.size());
while(listIterator.hasPrevious()) {
System.out.print(listIterator.previous() + " ");
}
System.out.println();
}
}
for-each 반복문으로 값을 출력 가능하며 get() 메도스로 인덱스를 통해 순차적으로 출력할 수도 있다.
그리고 Iterator, ListIterator를 통해 값을 출력할 수 있다. ListIterator 같은 경우에는 ArryList 크기를 입력해주고 역순으로 출력할 수 있다.
//for-each
Black White Green Red
//for
Black White Green Red
//Iterator
Black White Green Red
//ListIterator + colors.size()
Red Green White Black
이와 같이 출력이 될 것이다.
import java.util.ArrayList;
import java.util.Arrays;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
boolean contains = colors.contains("Black");
System.out.println(contains);
int index = colors.indexOf("Blue");
System.out.println(index);
index = colors.indexOf("Red");
System.out.println(index);
}
}
값에 유무를 알고 싶을 때 contains()를 사용한다. 값이 존재할 경우 true를, 값이 없을 경우 false를 리턴한다.
그리고 값이 존재하는 위치를 알고 싶을 때는 indexOf()을 사용하면 된다. 값이 존재하면 해당 값의 인덱스를 리턴하고 없을 경우 -1을 리턴하기 때문에 별도로 처리가 가능하다.
[toString]
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Black");
colors.add("Green");
String str = colors.toString();
System.out.println(str);
toString()
은 리스트를 문자열로 변환한다.
[Red, Black, Green]
이와 같이 대괄호 안에 값이 출력이 된다.
[반복문 & +]
import java.util.ArrayList;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Black");
colors.add("Green");
String str = "";
for(String item : colors) {
str += item + ",";
}
System.out.println(str);
}
}
만약 대괄호 없이 값을 출력하고 싶다면 반복문과 +
를 사용하면 된다.
Red, Black, Green
이와 같이 출력이 가능하다.
[join()]
import java.util.ArrayList;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Black");
colors.add("Green");
String str = String.join(",", colors);
System.out.println(str);
}
}
String.join();
로 간단하게 값을 출력할 수도 있다.
`Red, Black, Green'
[StringBuilder & 반복문 & +]
import java.util.ArrayList;
public class Testing {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Black");
colors.add("Green");
StringBuilder sb = new StringBuilder();
for(String item : colors) {
sb.append(item);
sb.append(",");
}
System.out.println(sb.toString());
}
}
StringBuilder과 반복문을 이용해 값을 출력할 수 있다. 위에 반복문과 +
을 사용한 방식과 같다.
Red, Black, Green
ref