How to swap objects in Java?
Suppose we have a class named " Car" which has some properties. Then we created two Car objects, for example, car1 and car2, how to exchange the data of car1 and car2?
Swapping or exchanging objects in Java involves swapping the references of two objects. In Java, objects are passed by reference, which means that the reference of the object is passed to a method or function, rather than the actual object itself. Therefore, swapping two objects involves exchanging their references.
One way to swap objects in Java is by using a temporary variable. Here's an example:
// Create two objects String object1 = "Hello"; String object2 = "World"; // Swap the objects using a temporary variable String temp = object1; object1 = object2; object2 = temp; // Output the swapped objects System.out.println(object1); // Output: World System.out.println(object2); // Output: Hello
In the above example, we created two String objects object1
and object2
. We then swapped the objects by using a temporary variable temp
to store the value of object1
, then assigned object2
to object1
, and finally assigned temp
to object2
.
Another way to swap objects is by using the Collections.swap()
method in the java.util
package. This method swaps the elements at the specified positions in a list. Here's an example:
// Create a list of objects List list = new ArrayList<>(); list.add("Hello"); list.add("World"); // Swap the objects using the Collections.swap() method Collections.swap(list, 0, 1); // Output the swapped objects System.out.println(list.get(0)); // Output: World System.out.println(list.get(1)); // Output: Hello
In the above example, we created a list of String objects list
and added two elements to it. We then swapped the objects by using the Collections.swap()
method and passing the list and the indices of the elements to be swapped.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.