Changes to <Entry> base list not showing up in map parent?
public static void main(String[] args){
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("a", 1);
myMap.put("b", 7);
myMap.put("c", 2);
myMap.put("b", 5);
List<Entry<String, Integer>> myList = mySort(myMap); //sort by map values!
//myList is now sorted but myMap is not!
}
public List<Entry<String,Integer>> mySort(Map<String, Integer> map){
Set<Entry<String,Integer>> set = map.entrySet();
List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(set);
Collections.sort(list, new Comparator<Entry<String, Integer>>()
{
public int compare(Entry<String,Integer> o1, Entry<String, Integer> o2){
return (o2.getValue()).compareTo(o1.getValue());
}
}
);
return list;
}
My question is: after calling the sort (in the last line of the main function), if I print my list, I see that it is sorted correctly. But what happens with myMap- if I check it, I still find it unsorted! Since the list was created by "copying by reference" from a set of objects on the map, should the changes in the list also reflect on the map?
+4
2 answers