[자바 컬렉션과 Stream] 75. ArrayList

김건우's avatar
Feb 19, 2025
[자바 컬렉션과 Stream] 75. ArrayList
ArrayList<String> list = new ArrayList<String>(); ArrayList<Integer> list = new ArrayList<Integer>();

객체에 데이터를 저장하려면 add()

list.add("MILK"); list.add("BREAD"); list.add("BUTTER");

새로운 데이터는 중간에 삽입

list.add(1, "APPLE");

특정한 위치에 있는 원소를 바꾸려면 get()

list.set(2, "GRAPE");

데이터를 삭제하려면 remove()

list.remove(3);

객체에 저장된 객체를 가져오는 메소드는 get()

String s = list.get(0);

예제 1. 객체를 ArrayLIst에 저장하기

package ex16; // 객체를 arraylist에 저장하기 import java.util.ArrayList; class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } public class ArrayLIstTest { public static void main(String[] args) { ArrayList<Point> list = new ArrayList<>(); list.add(new Point(0, 0)); list.add(new Point(4, 0)); list.add(new Point(3, 5)); list.add(new Point(-1, 3)); list.add(new Point(13, 2)); System.out.println(list); } }
notion image

예제 2. 문자열을 ArrayList에 저장하기

package ex16; // 문자열을 arraylist에 저장하기 import java.util.ArrayList; public class ArrayListTest2 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Mango"); list.add("Pear"); list.add("Grape"); // arraylist에 저장된 문자열들을 검색한다 int index = list.indexOf("Apple"); System.out.println("사과의 위치:" + index); } }
notion image
Share article

gunwoo