gpt4 book ai didi

java - 按一个值对 java 对象集合进行排序,并按另一个值保持唯一性

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:25 24 4
gpt4 key购买 nike

我需要按整数值“level”对 java 对象集合进行排序。我还需要通过“标题”确定这个集合是否已经包含一个对象。

我认为集合的最佳选择是 TreeSet,它具有一组有序的唯一值。

我有一个具有“level”和“title”属性的对象。它的实现方式如下:

它覆盖了 Equals 方法(用于检查对象是否已按“title”包含在 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;
}

当我尝试将值添加到可能具有重复值的数组列表中的列表时。 contains 似乎不起作用,无论如何都将对象添加到 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); 进行排序。一旦你这样做,它应该一切正常。

原因是哈希表依赖于这样一个事实,即如果两个对象 equal() 那么它们的 hashCode() 相等。这是 hashCode()

的 javadoc 的摘录

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.

关于java - 按一个值对 java 对象集合进行排序,并按另一个值保持唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com