Sunday, 7 October 2018

                              cloning concept with list


package govind;

public class EmployeeData implements Cloneable {

private String empName;
private String empId;
public EmployeeData(String empName, String empId) {
super();
this.empName = empName;
this.empId = empId;
}
@Override
public String toString() {
return "EmployeeName="+empName+" "+"EmpId="+empId;
}


protected EmployeeData clone()
{
return new EmployeeData(empName, empId);
}



}


========================================================================================================================================


package govind;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class EmployeeDataList {

public static void main(String[] args) {
List<EmployeeData> original=Arrays.asList(new EmployeeData("govind","0105OIST"),
                                  new EmployeeData("sanjeev","0104RKDF"));
List<EmployeeData> copy=new ArrayList<>(original.size());
for(EmployeeData e:original)
{
copy.add(e.clone());
}

//In java 8
/*List<EmployeeData> copy1 = original.stream().map(EmployeeData::clone).collect(Collectors.toList());
System.out.println("copy1="+copy1);*/

System.out.println("original="+original);
System.out.println("copy="+copy);

}

}


===============================================================================================================================================
o/p:----------------------------------
original=[EmployeeName=govind EmpId=0105OIST, EmployeeName=sanjeev EmpId=0104RKDF]
copy=[EmployeeName=govind EmpId=0105OIST, EmployeeName=sanjeev EmpId=0104RKDF]

No comments:

Post a Comment