How to swap objects in Java?
Let’s say we have a class called “Car” with some attributes. And we create two objects of Car, say car1 and car2, how to exchange the data of car1 and car2?
A Simple Solution is to swap members. For example, if the class Car has only one integer attribute say “no” (car number), we can swap cars by simply swapping the members of two cars.
c1.no = 2 c2.no = 1
What if we don’t know members of Car?
The above solution worked as we knew that there is one member “no” in Car. What if we don’t know members of Car or the member list is too big. This is a very common situation as a class that uses some other class may not access members of other class. Does below solution work?
no = 1, model = 101 no = 2, model = 202
As we can see from above output, the objects are not swapped. We have discussed in a previous post that parameters are passed by value in Java. So when we pass c1 and c2 to swap(), the function swap() creates a copy of these references.
Solution is to use Wrapper Class If we create a wrapper class that contains references of Car, we can swap cars by swapping references of wrapper class.
no = 2, model = 202 no = 1, model = 101
So a wrapper class solution works even if the user class doesn’t have access to members of the class whose objects are to be swapped.
This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Java.util.Objects class in Java
- Classes and Objects in Java
- Different ways to create objects in Java
- Understanding Classes and Objects in Java
- Passing and Returning Objects in Java
- How are Java objects stored in memory?
- Comparison of Autoboxed Integer objects in Java
- equals() on String and StringBuffer objects in Java
- Count number of a class objects created in Java
- Using TreeMap to sort User-defined Objects in Java
- How to prevent objects of a class from Garbage Collection in Java
- Swap two variables in one line in C/C++, Python, PHP and Java
- Collections swap() method in Java with Examples
- Swap two Strings without using third user defined variable in Java
- Swapping items of a list in Java : Collections.swap() with Example