Java์์ ArrayList๋ ๋์ ๋ฐฐ์ด์ ๊ตฌํํ ํด๋์ค์ด๋ค. ์ด ํด๋์ค๋ ๋ฐฐ์ด๋ณด๋ค ํฌ๊ธฐ๊ฐ ๊ฐ๋ณ์ ์ด์ด์ ํ์์ ๋ฐ๋ผ ์์๋ฅผ ์ถ๊ฐํ๊ฑฐ๋ ์ ๊ฑฐํ ์ ์๋ค. ArrayList๋ java.util ํจํค์ง์ ํฌํจ๋์ด ์๋ค.
list.add(์ถ๊ฐํ ๊ฐ);
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// ArrayList ์์ฑ
ArrayList<String> list = new ArrayList<>();
// ์์ ์ถ๊ฐ
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// ์ถ๋ ฅ
System.out.println(list); // [Apple, Banana, Cherry]
}
}
list.get(์ธ๋ฑ์ค);
// ํน์ ์ธ๋ฑ์ค์ ์์ ์ ๊ทผ
String firstElement = list.get(0);
System.out.println("์ฒซ ๋ฒ์งธ ์์: " + firstElement); // Apple
list.set(์ธ๋ฑ์ค, ์์ ๊ฐ)
// ํน์ ์ธ๋ฑ์ค์ ์์ ์์
list.set(1, "Blueberry");
System.out.println(list); // [Apple, Blueberry, Cherry]
list.remove(์ธ๋ฑ์ค)
// ํน์ ์ธ๋ฑ์ค์ ์์ ์ญ์
list.remove(2); // Cherry ์ญ์
System.out.println(list); // [Apple, Blueberry]
list.size()
// ArrayList์ ํฌ๊ธฐ ํ์ธ
int size = list.size();
System.out.println("๋ฆฌ์คํธ ํฌ๊ธฐ: " + size); // 2
list.contains(๊ฐ)
// ์์๊ฐ ๋ฆฌ์คํธ์ ํฌํจ๋์ด ์๋์ง ํ์ธ
boolean hasApple = list.contains("Apple");
System.out.println("๋ฆฌ์คํธ์ Apple์ด ํฌํจ๋์ด ์๋์? " + hasApple); // ๋ฆฌ์คํธ์ Apple์ด ํฌํจ๋์ด ์๋์? true
// ArrayList์ ๋ชจ๋ ์์ ๋ฐ๋ณต
for (String fruit : list) {
System.out.println(fruit);
// Apple
// Blueberry
}
Arrays.asList()
// ๋ฏธ๋ฆฌ ์ง์ ๋ ์์๋ก ArrayList ์ด๊ธฐํ
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(numbers); // [1, 2, 3, 4, 5]