사용자 정의 객체 리스트 요소 교환 (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)]