-1

I wanted to sort ArrayList and sorting should be done on copy of ArrayList.

I have tried following but it is sorting an original list and whatever changes i am making on sorted list it is reflecting in original list too.

List <Stud>  list = new ArrayList<>();
list.add( new Stud(1,"Sachin")  );
list.add( new Stud(2,"Niteen")  );
Set <Stud> set = new HashSet<>( list );
Stud s = set.iterator().next();
System.out.println( "S:"+s );
s.setRoll( 10 );
System.out.println( "list: "+list );
System.out.println( "set : "+set );

roll no 10 is set in both arraylist and set, how to avoid that. and it is helpful if you explain why it is happening.

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
  • 2
    You have added the same instance of `Stud` in both collections. Maybe you should call `setRoll` on something else (separate the mutable data from the student's(?) identity information). Maybe the Set should just have the id numbers? Hard to tell without knowing more about your project. – Thilo Aug 26 '17 at 08:46
  • Take a look here: https://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents – algrid Aug 26 '17 at 08:50
  • And the title has no relation with your question – Juan Carlos Mendoza Aug 26 '17 at 11:47

2 Answers2

0

When you use copy constructor on collection it creates new collection and adds all elements from old one. What you need is copy the elements, use forEach() for that purpose and create copies of elements.

vk23
  • 468
  • 7
  • 16
0
    List <Stud>  list = new ArrayList<>();
    list.add( new Stud(1,"Sachin")  );
    list.add( new Stud(2,"Niteen")  );
    Set <Stud> set = new HashSet<>();
    //copy using forEach
    for(Stud s : list){
        set.add(new Stud(s.getRoll(),s.getName()));
    }
    Stud s = set.iterator().next();
    System.out.println( "S:"+s );
    s.setRoll( 10 );
    System.out.println( "list: "+list);
    System.out.println( "set : "+set );

I'm not sure about your project, but this seems to be the only way of doing it. You are creating two objects and using the same in two different collection instances. Even though collection instances are different, your underline objects are the same. So if you change one of its properties, it reflects in all the collection instances you using. So, only way to clone them by referring to new Stud object as given above.

Rahul Raj
  • 3,197
  • 5
  • 35
  • 55