gpt4 book ai didi

java - HashSet 不会拒绝第二次添加调用

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

我刚开始使用 Collection,我已经编写了代码来测试 HashSet

这是代码(Person.java):

public class Person
{
int id;

public Person(int id)
{
this.id=id;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id=id;
}

public boolean equals(Object o)
{
if (o instanceof Person)
{
Person p=(Person)o;
if (this.id==p.id)
return false;
else
return true;
}
else return false;
}

public int hashCode()
{
return 21*id;
}
}

还有实现类,只是一个简单的类:

import java.util.*;

class HashSetTest
{
public static void main(String[] args)
{
Set<Person> set=new HashSet<Person>();
Person p1=new Person(6);
Person p2=new Person(6);
System.out.println(set.add(p1));
System.out.println(set.add(p2));
}
}

如果我没记错,第二个 System.out.println 语句应该返回 false,因为它不应该添加元素,因为它是重复的,但它返回 true。

最佳答案

似乎 Person.equals 方法在元素匹配时返回 false

应该是

if (this.id==p.id)
return true;
else
return false;

关于java - HashSet 不会拒绝第二次添加调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980950/

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