소개
Java 에서 기본 데이터 타입 (primitive data types) 의 교환은 간단하며, 변수 할당을 통해 쉽게 수행할 수 있습니다. 하지만 객체와 같은 비기본 데이터 타입 (non-primitive data types) 의 교환은 복잡할 수 있습니다. 다행히도 java.util.Collections 클래스에는 기본 및 비기본 데이터 타입의 리스트에서 요소를 쉽게 교환할 수 있는 swap() 메서드가 포함되어 있습니다. 이 Lab 에서는 Collections.swap() 메서드를 사용하여 swap 함수를 만드는 방법을 배우게 됩니다.
Java 파일 생성
먼저, ~/project 디렉토리에 SwapFunction.java라는 이름의 Java 파일을 생성합니다.
touch ~/project/SwapFunction.java
java.util 라이브러리 import
Java 파일에서 Collections 클래스를 사용하기 위해 java.util 라이브러리를 임포트합니다.
import java.util.*;
어떤 데이터 타입의 리스트를 받는 함수 선언
모든 데이터 유형의 리스트를 허용하는 함수를 선언합니다. Java 의 제네릭 (Generics) 기능을 사용하여 데이터 유형을 지정할 수 있습니다. 이 예제에서는 String 객체의 ArrayList를 받아 지정된 인덱스에서 두 요소를 바꾸는 swapElements라는 함수를 만들 것입니다.
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
// swap code goes here
}
}
Collections.swap() 메서드를 사용하여 swap 함수 구현
swapElements 함수에서 Collections.swap() 메서드를 사용하여 지정된 인덱스에 있는 요소를 바꿉니다.
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
Collections.swap(list, index1, index2);
}
}
swap 함수 테스트
String 객체의 ArrayList를 생성하고, 몇 가지 요소를 추가한 다음 두 요소를 바꿔서 swapElements 함수를 테스트합니다.
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
Collections.swap(list, index1, index2);
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi"));
System.out.println("Before Swap: " + list);
swapElements(list, 0, 2);
System.out.println("After Swap: " + list);
}
}
Java 파일을 저장한 다음 컴파일하고 실행합니다.
javac ~/project/SwapFunction.java && java SwapFunction
다음과 같은 출력을 볼 수 있습니다.
Before Swap: [apple, banana, orange, kiwi]
After Swap: [orange, banana, apple, kiwi]
리스트에서 여러 요소 교환 (Swap) 구현
swapElements 함수는 Collections.swap() 메서드를 여러 번 호출하여 리스트에서 여러 요소를 바꾸는 데에도 사용할 수 있습니다.
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
Collections.swap(list, index1, index2);
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi"));
System.out.println("Before Swap: " + list);
swapElements(list, 0, 3);
swapElements(list, 1, 2);
System.out.println("After Swap: " + list);
}
}
Java 파일을 저장한 다음 컴파일하고 실행합니다.
javac ~/project/SwapFunction.java && java SwapFunction
다음과 같은 출력을 볼 수 있습니다.
Before Swap: [apple, banana, orange, kiwi]
After Swap: [kiwi, orange, banana, apple]
예외 처리 (Exception Handling) 방법
지정된 인덱스가 리스트의 범위를 벗어나는 경우, swapElements 함수는 IndexOutOfBoundsException 예외를 발생시킵니다. 이를 처리하기 위해 함수에 try-catch 블록을 추가합니다.
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
try {
Collections.swap(list, index1, index2);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi"));
System.out.println("Before Swap: " + list);
swapElements(list, 0, 4); // out of bounds index
swapElements(list, 1, 2);
System.out.println("After Swap: " + list);
}
}
Java 파일을 저장한 다음 컴파일하고 실행합니다.
javac ~/project/SwapFunction.java && java SwapFunction
다음과 같은 출력을 볼 수 있습니다.
Before Swap: [apple, banana, orange, kiwi]
Error: Index 4 out of bounds for length 4
After Swap: [apple, orange, banana, kiwi]
배열 요소 교환 (Swap) 구현 방법
swapElements 함수를 사용하여 배열을 리스트로 변환하여 배열의 요소를 바꿀 수도 있습니다.
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
try {
Collections.swap(list, index1, index2);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "kiwi"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
System.out.println("Before Swap: " + list);
swapElements(list, 0, 3);
swapElements(list, 1, 2);
System.out.println("After Swap: " + list);
}
}
Java 파일을 저장한 다음 컴파일하고 실행합니다.
javac ~/project/SwapFunction.java && java SwapFunction
다음과 같은 출력을 볼 수 있습니다.
Before Swap: [apple, banana, orange, kiwi]
After Swap: [kiwi, orange, banana, apple]
사용자 정의 객체 리스트 요소 교환 (Swap) 방법
swapElements 함수는 사용자 정의 객체 리스트에서 요소를 바꾸는 데에도 사용할 수 있습니다. name과 age 필드를 가진 Person 클래스를 정의한 다음, Person 객체의 리스트를 생성하고 리스트에서 두 요소를 바꿉니다.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return name + " (" + age + ")";
}
}
public class SwapFunction {
public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
try {
Collections.swap(list, index1, index2);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 30));
list.add(new Person("Charlie", 35));
list.add(new Person("David", 40));
System.out.println("Before Swap: " + list);
swapElements(list, 0, 3);
swapElements(list, 1, 2);
System.out.println("After Swap: " + list);
}
}
Java 파일을 저장한 다음 컴파일하고 실행합니다.
javac ~/project/SwapFunction.java && java SwapFunction
다음과 같은 출력을 볼 수 있습니다.
Before Swap: [Alice (25), Bob (30), Charlie (35), David (40)]
After Swap: [David (40), Charlie (35), Bob (30), Alice (25)]
요약
이 랩에서는 Collections.swap() 메서드를 사용하여 Java swap() 함수를 만드는 방법을 배웠습니다. 임의의 데이터 유형의 리스트를 허용하는 함수를 만드는 방법, Collections.swap() 메서드를 사용하여 지정된 인덱스에서 두 요소를 바꾸는 방법, 그리고 예외를 처리하는 방법을 배웠습니다. 또한 배열과 사용자 정의 객체 리스트에서 요소를 바꾸는 방법도 배웠습니다.



