开发者

Methods override in hashset

I have developed one application which can using hashset concept. I have to override the equals(), h开发者_运维问答ashCode() and toString() methods in hashset. I dont know exactly why to override the given methods. Kindly anyone tell me what happen without override the above methods.


For example read this: http://www.javamex.com/tutorials/collections/hash_code_equals.shtml

There is plenty of discussions about the subject elsewhere (I recommend Effective Java book).

You do not need to override toString(), it's a bonus.

Basically if you don't override equals, you will not be able to get things from the collections the way you would expect. E.g. if your String class didn't have equals implemented in a meaningful way, collection.get("abc") and collection.get(new String("abc")) would give you different results.


How about

public class MyHashSet<E> extends HashSet<E> {
    @Override public int hashCode() { ... }
    @Override public String toString() { ... }
    @Override public boolean equals(Object o) { ... }
}

The same approach applies for objects you want to store in a HashSet

public class MyObject {
    @Override public int hashCode() { ... }
    @Override public String toString() { return "MyObject"; }
    @Override public boolean equals(Object o) { return this.equals(o); }
}

// Sample usage
HashSet<MyObject> set = ...
set.add(new MyObject());


Assuming that you want to override the objects that you will use, in the HashSet, rather than the methods in HashSet itself, the reason to do so is that you will get the expected results from putting objects in the HashSet. hashCode() in particular is critical for the proper functioning of HashSet, as is equals(). The main reason to override toString() is that you'll get some representation that makes sense for that object, rather than the default Object version of the method.

Essentially, if you don't override the methods, HashSet won't do what you expect. For example, say I have a class Foo where I haven't overriden the methods.

public class Foo {
    private int number;

    public Foo(int newNumber) {
       number = newNumber;
    }

    public int getNumber() {
        return number;
    }
}

I create two objects Foo1 and Foo2 that are equal in all respects, but I haven't overriden equals() or hashCode().

Foo foo1 = new Foo(10);
Foo foo2 = new Foo(10);

Java will not consider these to be equal, even though I can see that they are equal, because I haven't explained how to compare them by overriding equals(). If I print out the value for hashCode(), I'll see different integer values that have been assigned to the distinct objects, like this:

foo1 = 1671711
foo2 = 11394033

So if I add them to the HashSet, it will happily put both objects in there when I really only expected one of them to be put in.

Here is a similar question phrased in terms of an interview question about using these methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜