gpt4 book ai didi

java - LinkedHashSet 不删除重复项

转载 作者:行者123 更新时间:2023-11-29 05:25:54 25 4
gpt4 key购买 nike

我正在尝试创建一种搜索算法,将坐标对存储在名为 HashSquareSpec 的包装类中。为了避免重复并保持插入顺序,我将每个 HashSquareSpec 插入到 LinkedHashSet 中。即使我已经覆盖了 equals() 方法和 hashCode() 方法,LinkedHashSet 仍然接受两个 HashSquareSpec 对象相同的坐标对。

public static void main(String [] args)
{
LinkedHashSet<HashSquareSpec> firedShots = new HashLinkedSet<HashSquareSpec>();
HashSquareSpec a = new HashSquareSpec(1,2);
HashSquareSpec b = new HashSquareSpec(2,2);
HashSquareSpec c = new HashSquareSpec(1,2);
HashSquareSpec d = new HashSquareSpec(3,2);

firedShots.add(a);
firedShots.add(b);
firedShots.add(c);
firedShots.add(d);
System.out.println(a.equals((SquareSpec)c));
Iterator l = firedShots.iterator();
while(l.hasNext())
{
System.out.println(l.next().hashCode());
}
}

Output:
true
38444474
38474265
38444474
38504056

HashSquare 类

public class HashSquareSpec extends SquareSpec 
{
public HashSquareSpec(int sx, int sy)
{
super(sx,sy);
}

public HashSquareSpec(String codeString)
{
super(codeString);
}

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

public boolean equals(HashSquareSpec other)
{
if(this.toString().equals(other.toString()))
return true;
else
return false;
}
}

和 HashSquareSpec 的父类(super class)

public class SquareSpec {
public int x;
public int y;

public SquareSpec(int sx, int sy) {
this.x = sx;
this.y = sy;
}

public SquareSpec(String codeString) {
this.x = Integer.parseInt(codeString.substring(1,2));
this.y = Integer.parseInt(codeString.substring(3,4));
}

public String toString() {
return("(" + x + "," + y + ")");
}

public boolean equals(SquareSpec other) {
return (other.x == this.x &&
other.y == this.y );
}
}

尽管有许多不同的 hashCode 变体和 Eclipse equals 以及 hashCode 生成,firedShots 数据结构不断接受重复项。我的代码有什么问题?

最佳答案

你在正确的轨道上,重写了 hashcodeequals,只是你错误地重写了 equals method from ObjectHashSquareSpec(和 SquareSpec)中。参数必须是 Object。因为它没有被覆盖,Object 中的 equals 被调用,它比较对象引用以查看它们是否是同一个对象。它们不是,因此允许“重复”。

尝试:

@Override
public boolean equals(Object other)
{
if(this.toString().equals(other.toString()))
return true;
else
return false;
}

您还应该测试 other 是否为 null,然后确保 other 是同一类型。

包括 @Override 注释,这样如果该方法实际上没有覆盖任何东西,编译器就会报错。

关于java - LinkedHashSet 不删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22701608/

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