Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Java/자바] ArrayList 요소 위치 바꾸기(Swap): Collections 클래스 활용 본문
ArrayList에서 요소의 위치를 바꾸는 것은 종종 필요한 작업 중 하나입니다. Java의 Collections 클래스를 사용하여 ArrayList 요소의 위치를 바꾸는 여러 가지 방법을 알아보겠습니다.
예제 1: Collections.swap() 메서드 사용
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
System.out.println("Original List: " + numbers); // Original List: [1, 2, 3, 4, 5]
Collections.swap(numbers, 0, 4);
System.out.println("After swapping: " + numbers); // After swapping: [5, 2, 3, 4, 1]
이 예제에서는 Collections 클래스의 swap() 메서드를 사용하여 numbers 리스트의 첫 번째 요소와 마지막 요소의 위치를 바꿉니다.
예제 2: 직접 구현하여 위치 바꾸기
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println("Original List: " + colors); // Original List: [Red, Green, Blue]
int index1 = 0;
int index2 = 2;
String temp = colors.get(index1);
colors.set(index1, colors.get(index2));
colors.set(index2, temp);
System.out.println("After swapping: " + colors); // After swapping: [Blue, Green, Red]
이 예제에서는 직접 구현하여 ArrayList의 요소 위치를 바꿉니다.
'프로그래밍' 카테고리의 다른 글
[Java/자바] 10진수를 16진수로 변환하는 방법 (0) | 2024.03.07 |
---|---|
[Java/자바] char를 ASCII 숫자 값으로 변환하는 방법 (0) | 2024.03.07 |
[Java/자바] 리스트를 두 개의 리스트로 나누기: sublist() 메서드 활용 (0) | 2024.03.07 |
[Java/자바] ArrayList 요소 값 변경 방법: replaceAll() 메서드 (0) | 2024.03.07 |
[Java/자바] String 리스트에서 null 및 빈 문자열 제거하기 (0) | 2024.03.07 |