简体   繁体   English

为什么我的班在Java HashSet中不能正常工作?

[英]Why does my class not work properly in a Java HashSet?

I am working on a project that involves me using a HashSet of a class I made, which I will name Test . 我正在使用一个我HashSet的类的HashSet进行涉及我的项目,我将其命名为Test I defined the stated HashSet like so: 我像这样定义了声明的HashSet

HashSet<Test> t = new HashSet<Test>();
t.add(new Test("asdf", 1));
t.add(new Test("hello", 2));
t.add(new Test("hello", 3));

I tried using 我尝试使用

t.contains(new Test("asdf", 1));

but it returns false . 但它返回false However, when I use a HashSet<Character> it seems to work fine. 但是,当我使用HashSet<Character>它似乎可以正常工作。 I tried overriding the previous equals declaration, but it didn't work. 我尝试覆盖以前的equals声明,但是没有用。 I tried leaving equals alone, but i still got false . 我试着equals人,但我还是false I need to know what i am doing wrong? 我需要知道我在做什么错吗?

also, i did not edit the hash function, i only changed Test.equals(Object o). 另外,我没有编辑哈希函数,只更改了Test.equals(Object o)。 It's a simple project and since the java documentation states that it uses o.equals(this), i thought i would not have to. 这是一个简单的项目,并且由于Java文档指出它使用了o.equals(this),所以我认为我不必这样做。

您可能还必须重载hashCode()方法。

HashSet.add(Object data) is not equal to HashSet.add(new Test(String, int)) HashSet.add(Object data)不等于HashSet.add(new Test(String, int))

Try to use HashSet.add(new Test("asdf", 1)); 尝试使用HashSet.add(new Test("asdf", 1)); . And make overrides from the hashCode() method. 并从hashCode()方法进行覆盖。 Does your code compile? 您的代码可以编译吗?

Your code will not even compile... 您的代码甚至无法编译...

HashSet does not have an add() method which accepts two arguments. HashSet没有可以接受两个参数的add()方法。

If you mean 如果你的意思是

t.add(new Test("asdf", 1));

in stead of 代替

t.add("asdf", 1);

be sure the hashcode and equals method of the Test class are implemented properly, as said before. 如前所述,确保Test类的hashcode和equals方法正确实现。

Internally a hashtable will use Object#hashCode(), to hash and bucket your objects, and Object#equals() to test for equality if there are hashCode clashes. 在内部,哈希表将使用Object#hashCode()来哈希和存储对象,并使用Object#equals()来测试是否存在hashCode冲突是否相等。 You need to ensure that your Test class provides suitable implementations (overrrides) these, in your case to test for string equality, otherwise the default Object#equals() method will use the objects instance identity (ref id). 您需要确保Test类提供适当的实现(覆盖),以测试字符串是否相等,否则默认的Object#equals()方法将使用对象实例标识(引用ID)。 See here for a tutorial on this topic. 有关此主题的教程,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM