Swap elements in a list of custom objects
The swapElements
function can also be used to swap elements in a list of custom objects. Define a Person
class with name
and age
fields, then create a list of Person
objects, and swap two elements in the list.
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);
}
}
Save the Java file, then compile and run it.
javac ~/project/SwapFunction.java && java SwapFunction
You should see the following output:
Before Swap: [Alice (25), Bob (30), Charlie (35), David (40)]
After Swap: [David (40), Charlie (35), Bob (30), Alice (25)]