执行比较我有这样的和平代码:元素后取出在TreeSet中
final SortedSet<NisType> lAllNNisType = new TreeSet<NisType>(new NisTypeComparator());
lAllNisType.addAll(pAllNisType); // where pAllNisType is of type ArrayList<NisType>
这就是我比较类:
private class NisTypeComparator implements Comparator<NisType> {
@Override
public int compare(NisType pNisType, NisType pNisType2) {
if (pNisType.getPrio()>pNisType2.getPrio())
return 1;
else if (pNisType.getPrio()<pNisType2.getPrio())
return -1;
else
return 0;
}
}
我的ArrayList pAllNisType
充满了6个不同的对象(基于平等和hashCode方法)。 后然而这一行被执行:
lAllNisType.addAll(pAllNisType);
lAllNisType
只包含5个对象。 有一个比较返回0.并且由于这一个对象已从lAllNisType
中删除。
我不知道这里发生了什么。 对象不同。如果我做这样的事情:
final Set<NisType> lAllNisType = new HashSet<NisType>(pAllNisType);
lAllNisType
有6个元素。
感谢您的帮助
斯特凡
然后你的'比较器'比较不同于'equals'和'hashCode'。当然是 – 2014-10-20 15:18:51
。为什么这很重要? – 2014-10-20 15:20:22
这就解释了为什么你在'TreeSet'中有5个元素,而在'HashSet'中有6个元素。 – 2014-10-20 15:20:56