How to swap or exchange objects in Java?
Last Updated :
19 Nov, 2021
In order to understand how to swap objects in Java, let us consider an illustration below as follows:
Illustration:
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?
Methods:
- Using concepts of OOPS
- Using Wrapper classes of java
Method 1: Using concepts of OOPS
Here we will be simply swapping members for which let us directly take a sample 'Car' illustration with which we will play. So 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.
Example 1-A
Java
// Java program to demonstrate that we can swap two
// objects be swapping members
// Class 1
// Number class Car
class Car {
// Attributes associated with car
int no;
Car(int no) { this.no = no; }
}
// Class 2
// Uses Car objects
class GFG {
// Method 1
// To swap
public static void swap(Car c1, Car c2)
{
int temp = c1.no;
c1.no = c2.no;
c2.no = temp;
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating car class objects(creating cars)
Car c1 = new Car(1);
Car c2 = new Car(2);
// Calling method 1
swap(c1, c2);
// Print and display commands
System.out.println("c1.no = " + c1.no);
System.out.println("c2.no = " + c2.no);
}
}
Outputc1.no = 2
c2.no = 1
Note: Geek, 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?
Example 1-B
Java
// Java program to demonstrate that we can swap two
// objects be swapping members
// Where it does not work
// Class 1
// A car with number and name
class Car {
// Attributes of Car class
int model, no;
// Constructor
Car(int model, int no)
{
// This keyword is used to refer
// current instance itself
this.model = model;
this.no = no;
}
// Method of this class
// To print Car
void print()
{
// Printing number and model of car
System.out.println("no = " + no +
", model = " + model);
}
}
// Class 2
// A class that uses Car
class Main
{
// swap() doesn't swap c1 and c2
public static void swap(Car c1, Car c2)
{
Car temp = c1;
c1 = c2;
c2 = temp;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
Car c2 = new Car(202, 2);
swap(c1, c2);
c1.print();
c2.print();
}
}
Outputno = 1, model = 101
no = 2, model = 202
Output explanation: As we can see from the 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.
Method 2: Wrapper Class
If we create a wrapper class that contains references of Car, we can swap cars by swapping references of the wrapper class.
Example
Java
// Java program to Demonstrate that Wrapper Classes
// Can be Used to Swap two Objects
// Class 1
// A car with model and no.
class Car {
// Attributes associated with car
int model, no;
// Constructor of class 1
Car(int model, int no)
{
// This refers to current instance itself
this.model = model;
this.no = no;
}
// Method
// To print object details
void print()
{
System.out.println("no = " + no
+ ", model = " + model);
}
}
// Class 2
// Wrapper over class that is used for swapping
class CarWrapper {
Car c;
// Constructor
CarWrapper(Car c) { this.c = c; }
}
// Class 3
// Uses Car class and swaps objects of Car
// using CarWrapper
class GFG {
// This method swaps car objects in wrappers
// cw1 and cw2
public static void swap(CarWrapper cw1, CarWrapper cw2)
{
Car temp = cw1.c;
cw1.c = cw2.c;
cw2.c = temp;
}
// Main driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
Car c2 = new Car(202, 2);
CarWrapper cw1 = new CarWrapper(c1);
CarWrapper cw2 = new CarWrapper(c2);
swap(cw1, cw2);
cw1.c.print();
cw2.c.print();
}
}
Output:
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.
Similar Reads
Object Graph in Java Serialization In Java, Serialization is the process of converting an object into a format that can be easily stored or transmitted like a byte stream. When we think of Serialization, we probably think that a single object is being serialized, but what happens if the object contains references to other objects? Wi
4 min read
Classes and Objects in Java In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
11 min read
Understanding Classes and Objects in Java The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
10 min read
Collections swap() method in Java with Examples The swap() method of java.util.Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged. Syntax: public static void swap(List list, int i, int j) Parameters: This method takes
2 min read
Stack set() method in Java with Example The set() method of Java Stack is used to replace any particular element in the stack created using the Stack class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: public E set(int index
3 min read
Field set() method in Java with Examples The set() method of java.lang.reflect.Field is used to set the value of the field represented by this Field object on the specified object argument to the specified new value passed as parameter. The new value is automatically unwrapped if the underlying field has a primitive type. If the field is s
4 min read