简体   繁体   中英

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 . I defined the stated HashSet like so:

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 . However, when I use a HashSet<Character> it seems to work fine. I tried overriding the previous equals declaration, but it didn't work. I tried leaving equals alone, but i still got 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). It's a simple project and since the java documentation states that it uses o.equals(this), i thought i would not have to.

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

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

Try to use HashSet.add(new Test("asdf", 1)); . And make overrides from the hashCode() method. Does your code compile?

Your code will not even compile...

HashSet does not have an add() method which accepts two arguments.

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.

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. 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). See here for a tutorial on this topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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