HashSet 不保证其元素的任何顺序。如果您需要此保证,请考虑使用 TreeSet 来保存您的元素,但要通过键实现唯一性并保持恒定的时间覆盖hashCode()
并equals()
有效地寻找您想要的内容,如下所示:
class Item {
String key;
double score;
public Item(String key, double score) {
this.key = key;
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return key.equals(item.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
@Override
public String toString() {
return "Item{" +
"key='" + key + '\'' +
", score=" + score +
'}';
}
}
// main
public static void main(String[] args) {
Set<Item> itemSet = new HashSet<>();
itemSet.add(new Item("1", 1));
itemSet.add(new Item("1", 2));
itemSet.add(new Item("2", 1));
//to get a sorted TreeSet
//Add all your objects to the TreeSet, you will get a sorted Set.
//TreeSet myTreeSet = new TreeSet();
//myTreeSet.addAll(itemSet);
//System.out.println(myTreeSet);
}
输出 :
Item{key='1', score=1.0}
Item{key='2', score=1.0}