簡體   English   中英

Java哈希集包含重復項

[英]Java hashset contains duplicates

我有一個Car對象的哈希集,例如Set<Car> cars = new HashSet<Car>

汽車課簡要介紹如下

public abstract class Car {
  protected Piece current;
  protected Piece;
  ....
  ....
  ....
  @Override
  public booleanll) return false;
      if ((obj.getClass() == this.getClass())) {
        Car o = (Carrent.equals(o.current) && other.equals(o.other)) || (current.equals) && other.et)));
      }
      return false;
  }

  @Override
  public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result + ((current == null) ? 0 : current.hashCode());
      result = prime =pokmob result;
  }

正如您在上面看到的,Car是一個抽象類,因此我還有另外兩個類BigCarSmallCar擴展了Car抽象類。 我的集合包含BigCar和SmallCar對象。 還要注意,這些子類不會覆蓋equals和hashcode方法。

在您的hashCode方法中,這兩個字段不是對稱處理的-因此,交換了current車位和other位置的兩輛汽車將不會具有相同的哈希碼。

例如,您可以改用此方法(也請注意使用Objects::hash以避免進行空檢查):

@Override public int hashCode() {
  return Objects.hash(current) * Objects.hash(other);
}

好吧,在您的hashCode currentother不可互換。

讓分別表示current的值作為xother的值作為y一些實例。

hashCode值為31*(31+x)+y

現在,對於另一個實例,如果otherx並且currenty (這意味着第二個實例應該等於第一個實例),則hashCode現在為31*(31+y)+x ,不等於31*(31+x)+y適用於xy大多數值。

因此,您違反了hashCode的約定,因為如果a.equals(b) == true ,則a.hashCode()必須等於b.hashCode()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM