java - Sorting cusom type in Set (Set<MyType>) -
this question has answer here:
why can't collections.sort
set<mytype>
? code below. when use arraylist
this code works perfectly, when use kind of set
, error.
set<auto> set = new hashset<auto>(); set.add(auto1); set.add(auto2); set.add(auto3); set.add(auto4); set.add(auto5); collections.sort(set, new comparator<auto>() { @override public int compare(auto o1, auto o2) { return o1.getmarka().compareto(o2.getmarka()); } });
hashset
not ordered collection; in other words, not contain elements in order.
you can see hashset
bag contains objects. when stick hand in , pull out objects 1 one, don't know in order elements out. can't sort elements in bag - because bag doesn't keep them in order sorted them in.
the order of elements lost; sorting hashset
has no effect (besides fact collections.sort
takes list
instead of set
mureinik noticed, code doesn't compile).
if need elements in set
in specific, defined order, use different set
implementation, example treeset
.
Comments
Post a Comment