按一个值对对象的Java集合进行排序,并按另一个值保持唯一

我需要按整数值“级别”对对象的Java集合进行排序.我还需要确定该集合是否已按“标题”包含对象.

我相信集合的最佳选择是TreeSet具有一组有序的唯一值.

我有一个带有“级别”和“标题”属性的对象.它实现的可比性如下:

它重写Equals方法(用于检查对象是否已按“标题”包含在TreeSet中.

代码如下:

@Override
public boolean equals(Object arg0) {

    Artifact obj = (Artifact) arg0;

    if (this.getTitle().equals(obj.getTitle())) { 
        return true;
    }

    return false;
}

@Override
public int compareTo(Artifact aThat) {  

    final int BEFORE = -1;
    final int EQUAL = 0;
    final int AFTER = 1;

    if (this == aThat) return EQUAL;

    if (this.level < aThat.level) return BEFORE;
    if (this.level > aThat.level) return AFTER;

    assert this.equals(aThat) : "compareTo inconsistent with equals.";
    return EQUAL;
}

当我尝试从可能具有重复值的arraylist向列表中添加值时.包含似乎不起作用,并且无论如何都将对象添加到TreeSet中.这是代码:

TreeSet<Artifact> subsetOfArtifacts = new TreeSet<Artifact>();

ArrayList<Artifact> allArtifacts = getArtifacts(); 
Iterator<Artifact> allArtifactsIter = allArtifacts.iterator();

while (allArtifactsIter.hasNext()) {
    Artifact artifact = (Artifact) allArtifactsIter.next();
    if (!subsetOfArtifacts.contains(artifact)) {
        subsetOfArtifacts.add(artifact);
    }
 }

理想情况下,我想列出按级别排序的所有唯一工件.我该如何完成?

解决方法:

如果您覆盖equals(),那么您也应该覆盖hashCode()!否则,集合(尤其是集合)的行为是不确定的.您应该将此方法添加到您的类中:

@Override
public int hashCode() {
    return title.hashCode();
}

接下来,您应该改用HashSet并使用Set sortedSet = new TreeSet(set);用于排序.完成后,一切正常.

原因是HashTables依赖于以下事实:如果两个对象equal()相同,则它们的hashCode()也相等.这是摘自javadoc的hashCode()

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently
    return the same integer, provided no information used in equals
    comparisons on the object is modified. This integer need not remain
    consistent from one execution of an application to another execution
    of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must
    produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on
    each of the two objects must produce distinct integer results.
    However, the programmer should be aware that producing distinct
    integer results for unequal objects may improve the performance of
    hashtables.
上一篇:HashSet 和 TreeSet的区别


下一篇:TreeSet、TreeMap、Collections.sort()的区别,原理