728x90
반응형
SMALL
1. add(E e)
- 리스트의 끝에 요소 추가
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
System.out.println(list); // [10, 20]
1.1 add(int index, E e)
- 지정한 위치에 요소 삽입 (기존 요소는 뒤로 밀림)
list.add(1, 99); // 인덱스 1에 99 삽입
System.out.println(list); // [10, 99, 20]
1.2 a.addAll(b)
- 다른 리스트의 요소 추가
List<Integer> a = new ArrayList<>(List.of(1, 2));
List<Integer> b = new ArrayList<>(List.of(3, 4));
a.addAll(b);
System.out.println(a); // [1, 2, 3, 4]
a.addAll(1, List.of(9, 8));
System.out.println(a); // [1, 9, 8, 2, 3, 4]
2. get(int index)
- 지정한 인덱스의 요소 반환
int value = list.get(1); // 99
3. set(int index, E e)
- 인덱스 위치의 값을 새 값으로 교체
list.set(1, 42); // index 1의 값을 42로 변경
System.out.println(list); // [10, 42, 20]
4. remove(int index)
- 지정한 위치의 요소를 삭제
list.remove(1); // index 1 제거
System.out.println(list); // [10, 20]
5. remove(Object o)
- 지정한 값을 삭제 (처음 등장하는 값 하나만)
list.remove(Integer.valueOf(20));
System.out.println(list); // [10]
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 2));
list.remove(Integer.valueOf(2)); // 값 2 제거 (처음 등장하는 하나)
System.out.println(list); // [1, 3, 2]
int를 넣으면 오버로드된 remove(int index)로 해석되므로 Integer.valueOf()를 사용해야 함
6. size()
- 리스트에 담긴 요소 개수 반환
System.out.println(list.size()); // 1
7. isEmpty()
- 리스트가 비었는지 확인 (boolean 반환)
System.out.println(list.isEmpty()); // false
8. clear()
- 모든 요소 제거
list.clear();
System.out.println(list); // []
9. contains(Object o)
- 특정 값이 리스트에 존재하는지 확인
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
System.out.println(names.contains("Bob")); // true
List<String> list = new ArrayList<>(List.of("a", null, "b"));
System.out.println(list.contains(null)); // true
10. indexOf(Object o)
- 특정 값의 첫 번째 등장 위치 반환
- 없으면 -1 반환
System.out.println(names.indexOf("Bob")); // 1
System.out.println(names.indexOf("David")); // -1
11. lastIndexOf(Object o)
- 특정 값의 마지막 등장 위치 반환
List<String> list = new ArrayList<>(List.of("a", "b", "c", "a"));
System.out.println(list.lastIndexOf("a")); // 3
12. toArray()
- 리스트를 배열로 변환
Object[] arr = list.toArray();
System.out.println(Arrays.toString(arr)); // [a, b, c, a]
13. sort()
List<String> list = new ArrayList<>(List.of("banana", "Apple", "cherry", "apple"));
13.1 오름차순 (기본 정렬)
list.sort(Comparator.naturalOrder());
System.out.println(list);
// [Apple, apple, banana, cherry] (대문자가 소문자보다 앞)
13.2 내림차순
list.sort(Comparator.reverseOrder());
System.out.println(list);
// [cherry, banana, apple, Apple]
13.3 대소문자 무시하고 오름차순
list.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(list);
// [Apple, apple, banana, cherry]
13.4 사용자 정의 정렬 (길이순 정렬 등)
list.sort((a, b) -> a.length() - b.length());
System.out.println(list);
// [Apple, apple, banana, cherry]
13.5 숫자 리스트 정렬 예시
List<Integer> nums = new ArrayList<>(List.of(5, 3, 7, 1));
nums.sort(Comparator.naturalOrder()); // 오름차순
nums.sort(Comparator.reverseOrder()); // 내림차순
728x90
반응형
LIST