Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to swap or exchange objects in Java?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.58k
    Comment on it

    How to swap or exchange objects in Java?

    Wrapper Class can be used to swap or exchange objects in Java.

    A Java program using wrapper classes to swap objects.

    class Employee
    {
        int empno, salary;
        Car(int empno, int salary)  //Parameterized constructor
        {
            this.empno = empno;
            this.salary = salary;
        }
    
        void print()    //Method printing Employee details
        {
            System.out.println("Employee No. = " + empno +   ", salary = " + salary);
        }
    }
    
    // A Wrapper over class that is used for swapping
    
    class EmployeeWrapper
    {
       Employee e;
       EmployeeWrapper(Employee e)   
       {
        this.e = e;
       }
    }
    
    //A Class that use Employee and swaps objects of Employee using EmployeeWrapper
    
    class Main
    {
        // This method swaps Employee objects in wrappers ew1 and ew2
    
        public static void swap(EmployeeWrapper ew1, EmployeeWrapper ew2)
        {
            Employee temp = ew1.e;
            ew1.e = ew2.e;
            ew2.e = temp;
        }
    
        public static void main(String[] args)
        {
            Employee e1 = new Employee(1,1000);
            Employee e2 = new Employee(2, 2000);
            EmployeeWrapper ew1 = new EmployeeWrapper(e1);
            EmployeeWrapper ew2 = new EmployeeWrapper(e2);
            swap(cw1, cw2);
            ew1.e.print();
            ew2.e.print();
        }
    }
    

    Output:

    Employee No. =2,salary =1000
    Employee No. =1,salary =2000

    Explanation of above program:

    In this a wrapper class that contains references of Employee is created. Swapping references of wrapper class swaps Employee objects.So a wrapper class solution works even if the user class doesnt have access to members of the class whose objects are to be swapped.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: