In Java, handling non-primitive types (like objects) can be done using reference variables. Here are some key points to consider:
-
Reference Variables: Non-primitive types are stored as references. When you assign one object to another, you're copying the reference, not the actual object.
-
Swapping Objects: To swap non-primitive types, you can use the
Collections.swap()method from thejava.util.Collectionsclass. This method allows you to easily swap elements in a list.
Example:
Here's how you can swap two objects in a list:
import java.util.ArrayList;
import java.util.Collections;
public class SwapExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Before swap
System.out.println("Before swap: " + list);
// Swap elements at index 0 and 1
Collections.swap(list, 0, 1);
// After swap
System.out.println("After swap: " + list);
}
}
Output:
Before swap: [Apple, Banana, Cherry]
After swap: [Banana, Apple, Cherry]
This example demonstrates how to handle non-primitive types by swapping elements in a list. If you have further questions or need more examples, feel free to ask!
