Java : How to swap two objects [Problem Solved]

As you might knowJava does not support pointers, thus swapping things around could create problems.  In this post I will show an example of swapping two objects.

We have Employee class that holds information about Employees and SwapDemo3 class that will actually swap two employees inside a swap() method.

Swap() method will be using set and get methods of Employee class to get the private data from it.

So here is Employee Class we will be working with:

and here is SwapDemo3 class that swaps 2 employees using get and set methods of the Employee class.

Program output is:

 

Check out more posts on “Useful Java Functions and Tutorials”

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. Janey Smith

    Thanks for the info, been trying to figure that out for a while now:)

    1. Anatoly Spektor

      Glad you liked it :)

  2. Rakesh

    Good info. Like it. I am also trying if there is a way without using those getters and setters, we can swap the complete objects using Pass by reference…… :)

  3. pegasus

    Thanks! It’s useful

  4. deepak

    What if the number of attributes for a class is huge. Like, Employee class has attributes- employeeID;

    employeeName;
    address;
    startingYear, managername, salary, joindate,…..and many more such attributes. so swapping each variable will be tough. I think it can be done using cloning in java. or singleton classes . can u pls show how it can be done

  5. ilian

    What about swapping two elements from ArrayList or List? How to do it? Looks tedious compared to C/CPP!

  6. Deeann Wentland

    Hi there, You have done an excellent job. I will certainly digg it and personally suggest to my friends. I’m sure they will be benefited from this website.

  7. Shoaib Murtaza

    you are not swaping the objects but you are manipulating the objects

arrow