Recent Posts
간단명료
ArrayList 본문
Java의 List 인터페이스를 상속받은 클래스 중 하나.
배열은 크기가 고정인 반면 ArrayList는 가변적이다.
1. 생성
import java.util.ArrayList //필요
ArrayList<Integer> integers1 = new ArrayList<Integer>(); // 타입 지정
ArrayList<Integer> integers2 = new ArrayList<>(); // 타입 생략 가능
ArrayList<Integer> integers3 = new ArrayList<>(10); // 초기 용량(Capacity) 설정
ArrayList<Integer> integers4 = new ArrayList<>(integers1); // 다른 Collection값으로 초기화
ArrayList<Integer> integers5 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); // Arrays.asList()
2. 추가-add(), 변경-set()
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
// add() method
colors.add("Black");
colors.add("White");
colors.add(0, "Green"); //0번째에 추가되면서 기존 값들이 뒤로 밀림.
colors.add("Red");
// set() method
colors.set(0, "Blue"); //0번째 값(Green)을 Blue 로 변경
System.out.println(colors);
}
}
//결과
[Blue, Black, White, Red]
3. 삭제-remove()
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
String removedColor = colors.remove(0); //0 인덱스 삭제와 동시에 엘레멘트 값 리턴
System.out.println("Removed color is " + removedColor);
colors.remove("White"); //white 엘레멘트 삭제
System.out.println(colors);
colors.clear(); //전체 삭제
System.out.println(colors);
}
}
4. 검색-contains(), indexOf()
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
boolean contains = colors.contains("Black"); //포함하는 경우 true리턴
System.out.println(contains);
int index = colors.indexOf("Blue"); //포함하는 경우 값의 위치(index) 리턴(2개이상인 경우 제일 앞), 존재하지 않을 경우 -1
System.out.println(index);
index = colors.indexOf("Red");
System.out.println(index);
}
}
5. 출력-get()
728x90
반응형
'Java' 카테고리의 다른 글
List - Array 데이터 이동 (0) | 2022.02.16 |
---|---|
Pair (0) | 2022.02.16 |
Math 클래스 (0) | 2022.02.16 |
length, length(), size() (0) | 2022.02.16 |
charAt() (0) | 2022.02.16 |
Comments