为什么TreeSet在不相等的情况下删除重复项? [英] why does TreeSet remove duplicates when they are unequal?
问题描述
朋友,我在使用 TreeSet
获取全部数据时遇到问题。我已经将 TreeSet
排序为相同的值。
Friends, I am having a problem in getting entire data using TreeSet
. I have sorted the TreeSet
on some same values.
这是我的代码:
MyCars
类:
class MyCars implements Comparable<MyCars>{
private String number;
private int yearModel;
private double horsePower;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getYearModel() {
return yearModel;
}
public void setYearModel(int yearModel) {
this.yearModel = yearModel;
}
public double getHorsePower() {
return horsePower;
}
public void setHorsePower(double horsePower) {
this.horsePower = horsePower;
}
@Override
public int compareTo(MyCars c) {
return Double.compare(this.horsePower,c.getHorsePower());
}
}
SortTest
类:
public class SortTest {
void GoForSort(){
Set dataStructure=new TreeSet();
MyCars c1=new MyCars();
c1.setNumber("SRT-Viper123");
c1.setYearModel(2013);
c1.setHorsePower(450.00);
MyCars c2=new MyCars();
c2.setNumber("Chevrolet-Corvette901");
c2.setYearModel(2012);
c2.setHorsePower(450.00);
MyCars c3=new MyCars();
c3.setNumber("Ford-Mustang678");
c3.setYearModel(2014);
c3.setHorsePower(455.00);
dataStructure.add(c1);
dataStructure.add(c2);
dataStructure.add(c3);
Iterator<MyCars> it=dataStructure.iterator();
while(it.hasNext()){
MyCars c=it.next();
System.out.println(c.getNumber()+"\t"+c.getHorsePower()+"\t"+c.getYearModel());
}
}
public static void main(String[] args) {
SortTest st=new SortTest();
st.GoForSort();
}
}
您可以看到我已经基于horsePower对 TreeSet
进行了排序。而且我给了两个对象相同的马力值。
As you can see I have sorted the TreeSet
on the basis of horsePower. And I have given SAME value for horse-power to two objects.
这是我得到的输出:
SRT-Viper123 450.0 2013
Ford-Mustang678 455.0 2014
但是我也希望 Chevrolet-Corvette901
出现在这组输出中。为什么我不明白。
But I also want Chevrolet-Corvette901
to come in this set of output. Why I am not getting it.
有没有办法包含它?因为我发现将集合更改为 ArrayList
时没有问题。 TreeSet
仅排序唯一元素吗?
Is there any way to include that also? Because I found there was NO Problem when I change my collection to ArrayList
. Does TreeSet
sorts only unique elements?
是否有任何技巧可以获取&在迭代
期间打印所有对象,无论它们在 TreeSet
...
Is there any trick to get & print all objects during Iteration
regardless of their uniqueness in TreeSet
...
推荐答案
您有两个选择:
-
使您的
compareTo
还会比较number
和yearModel
字段。
在每个节点上存储一个集合(数组或 List
)-通常称为 MultiSet 。
Store a collection (array or List
) at each node - usually called a MultiSet.
只要您的 compareTo
报告两个项目是相等的,其中只有一个 >将出现在集合中。
So long as your compareTo
reports that two items are equal, only one of them will appear in the set.
这篇关于为什么TreeSet在不相等的情况下删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!