开发者

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",开发者_StackOverflow中文版 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.


You might have to overload the hashCode() method as well.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜