Class HashSet and hashCode method

I'm using a HashSet class with elements of class A.
I define the equals method but when i add a object which is already in the set, this object is duplicate.
Do i have to define the hashCode method in the class A? If yes, i don't understand why this method is used when adding a object.
Can you give me a explanation ?

Yes, you do. The hashCode method is used by HashSet and HashMap to find an object. See the API doc for Object, which explains the relationship between equals and hashCode.

Similar Messages

  • Comparing dynamic fields of objects using equals and hashCode methods

    To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
        Map<LocationData, List<LocationData>>
    The following is the class I used (its been shown to you so that it can be referred for my problem statement):
    LocationData class
        package com.astreait.bulkloader;
        public class LocationData {    
            String locId, deptId, jobTitleId, classificationId;
            @Override  
            public boolean equals(Object obj) {        
                LocationData ld = (LocationData)obj;       
                return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
        this.locId.equals(ld.locId);   
            @Override  
            public int hashCode() {        
                return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();  
    Problem:
    I'm already known to which all fields of this object I need to make the comparison.
    i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
    Need:
    I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
    I'm thinking what if I override the same two methods `equals() & hashCode();`
    such that the same can be achieved.
        TableClass class #1
        class TableClass{
            List<ColWithData> cwdList;
            @Override
            public boolean equals(Object obj) {
                boolean returnVal = false;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be compared
                return returnVal;
            @Override
            public int hashCode() {
                int returnVal = 0;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be found for their individual hashCodes
                return returnVal;
    ColWithData class #2
        class ColWithData{
            String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
            String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
    Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
    Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
        Map<TableClass, List<TableClass>> finalMap;

    Hello,
    What is the relation with the Oracle Forms tool ?
    Francois

  • Why Collection interface declares equals() and hashCode() method

    When I went through the source code of Collection interface, I found equals() and hashCode() are declared? Why? If a class implements this interface, it will inherit these two method from Object, and we can true to override them.

    It's probably so that they can provide the documentation that you see there.

  • Adding Objects To a HashSet, overriding equals and hashCode

    Hi everyone,
    I'm trying to add objects to a HashSet, using a string identifier (an attribute of these objects) to determine if two objects are equal.
    I have a class 'IntExpEvent' class that overrides the equals and hashCode methods.
    public class IntExpEvent implements ExperimentalEvent{
    public int correctAnswer;
    public String identifier;
    public IntExpEvent(String id, int correctAnswer){
         this.identifier = id;
         this.correctAnswer=correctAnswer;
    public String getID(){
         return(this.identifier);
    public boolean equals(ExperimentalEvent e){
         return (this.identifier.equals(e.getID()));
    public int hashCode(){
         System.out.println((this.getID()).hashCode());
         return (this.getID()).hashCode();
    private int hashCode=-1;
    public int hashCode() {
         if(hashCode==-1) {
         char[] ca=getID().toCharArray();
         for(int x=0;x<ca.length;x++) {
              hashCode+=ca[x];
         return(hashCode);
         IntExpEvent e1 = new IntExpEvent("test_IntExpEvent",4);
         IntExpEvent e2 = new IntExpEvent("test_IntExpEvent",6);
         HashSet hs = new HashSet();
         System.out.println(hs.add(e1));
         System.out.println(hs.add(e2));
    I can still add both e1 and e2 to the HashSet, which is what I'm trying to stop from happening. i.e. objects with the same identifier should be treated as the same object, allowing only one to be added to the HashSet. Does anyone know how I can do this? Help would be greatly appreciated

    In fact you don't override the equals method. The signature defined in the Object class is
      boolean equals(Object o)In your case it is
      boolean equals(ExperimentalEvent e)So instead of overriding the method you're overloading it.
    Regards

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • HashSet and my Objects

    I've created a number of objects for a project I'm working on, specifically, mySet, myNumber, and myString. These classes all extend a class called operand.
    I'm trying to insert them into a HashSet. I overloaded the equals and hashcode methods as such:
    myNumber:
         public int hashCode() {
              Double b = new Double(n);
              return b.hashCode();
         public boolean equals(myNumber a) {
              return (n == a.getVal() );
         }where n is a double containing the value of the number.
    myString:
         public int hashCode() {
              return getVal().hashCode();
         public boolean equals(myString a) {
              return getVal().equals(a.getVal());
         }where getVal() returns the string represented by the stringbuffer that stores the value of the myString object.
    They seem to work properly. I tried testing the myNumber class in this method of mySet.
    public boolean add(Object o) {
              if (o instanceof mySet) {
                   mySet a = (mySet) o;
                   Object[] b = a.stuff.toArray();
                   for (int i = 0; i < a.size(); i++) {
                        if (b[i] instanceof myNumber) {
                             if (stuff.add( (myNumber) b) ) {
                                  System.out.println( ((myNumber) b[i]).result() + " has been added");
                             Object[] v = stuff.toArray();
                             for (int j = 0; j < stuff.size(); j++) {
                                  if (b[i].equals((myNumber)v[j]))
                                       System.out.println("IT'S EQUAL");
                        else if (b[i] instanceof myString) {
                             if (stuff.add( (myString) b[i]) ) {
                                  System.out.println( ((myString) b[i]).result() + " has been added");
                   return true;
              else {
                   System.out.println("TypeException: improper operand types.");
                   System.out.println();
                   return false;
    this code prints the contents of the set:
    Object[] b = stuff.toArray();
              for (int i = 0; i < stuff.size(); i++) {
                   System.out.println( ((operand) b).result() + " " + Integer.toString( ((operand) b[i]).hashCode() ) );
    the output was:
    3 has been added
    IT'S EQUAL
    4 has been added
    IT'S EQUAL
    1 has been added
    IT'S EQUAL
    2 has been added
    IT'S EQUAL
    3 1074266112
    3 1074266112
    4 1074790400
    4 1074790400
    1 1072693248
    1 1072693248
    2 1073741824
    2 1073741824
    See, shouldn't the hashset NOT add the elements when they are equal and the hashcodes are the same? I don't understand why it does.

    You have not overridden the equals method. Instead you have defined a new equals method with different parameter. You must override the equals method that takes an Object as argument:
    public boolean equals(Object obj) {
      // your code here

  • Comparator question - changing Equals and HashCode too?

    Hi all I have an object test - this contains 2 variables:
    Int a; and Int b;Then there is a method called test() which returns a double and looks like this:
    public Double test()
    return a * (1d / b);
    }I have implemented the compareTo method do the "compareTo" test using the call to test() not on the fields directly e.g.
    this.test().compareTo(anotherObject.test()) instead of
    if (this.a != null && anotherDateInterval.a != null)
                compareTo = this.a.compareTo(anotherDateInterval.a);
            }Because I using the test() in the compareTo do I need to change the equals and hashcode method as well to reflect the use of test()?
    e.g.
    public boolean equals(Object obj)
       if (test() == null)
                if (other.test() != null)
                    return false;
            else if (!test().equals(other.test()))
                return false;
    }

    That depends if there are any class invarients that can be depended upon.
    The basic rule is that if .equals() returns true, then .compareTo() must return 0, but not necessarily the other way around. As long as this holds true, you don't really have to change .equals() or .hashCode(). If you're still using the identity equals method, then you probably don't have to worry about it. If you've overridden .equals() to be dependent upon a and b in some way, you probably do have to change the way .equals() works to make sure that .equals() doesn't return true if .compareTo() doesn't return 0.
    - Adam

  • Implementing equals() and hashcode

    Hi,
    I need to implement equals() and hashcode() in a class. I only need to use one class variable in the equals() method; String id.
    I'm having difficulties to understand the examples I've seen - can someone please help me out?
    regards, Puzz

    And I know you said you had a hard time understanding some examples, but I'm not sure which examples you've seen. Here is some recommended reading that I think explains this concept well:
    Sun's Java Tutorial: The equals and hashCode Methods
    Josh Bloch: Effective Java
    JavaWorld: Implementing equals and hashCode
    IBM: Defining hashCode() and equals() effectively and correctly
    JavaPractices: Implementing hashCode
    JavaWorld: override hashcode/equals
    ~

  • WebLogic 10.3 doesn't implements equals() and hashCode() for TimerHandle?

    Hi,
    I'm using WebLogic 10.3 and need to use TimerHandle to handle some logic in my application.
    Below is a scenario.
    At the time by creating EJB Timer, I've saved the TimerHandle for later use into Database along with specific name as a key.
    Then, at the time to execute/awaken timer I need to check that the saved TimerHandle is the same as passed Timer.
    @Timeout
    public void execute( final Timer timer )
    // getting key from passed object in timer.getInfo().
    // getting saved timerhandle by key. let's say dao.getXxxHandle(key);
    // perform checking.
    if ( timerHandle != null && timerHandle.equals( timer.getHandle() ) )
    // do sth.
    else
    //do another thing.
    The result is always drop in else block.
    By doing this is working on WAS7 and JBoss4xx (getting to if block). I was wondering if WebLogic doesn't implements equals and hashCode method then is there another way to check that the retrieved TimerHandle is the same one as timer.getHandle()?
    I'm thinking of adding some unique ID to see if timehandle is the same one or not? However as I mentioned, It works on WAS and JBoss. Does WebLogic has another way to handle my scenario?
    Any help would be appreciate.
    Thanks in advance,
    Nattachai W.

    As you have suggested, it looks like we don't override the equals() method on either our local or clustered TimerHandle implementations.
    We opened a bug (9558396) so we can address it in a future patchset.
    In the meantime, if you have an Oracle support contract, you could open a service request and ask for a patch for bug 9558396 to be created.
    -steve-

  • HashCode method

    How to write overridden hashcode method? Is there any particular rule for it?

    Folks,
    It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. My two bobs worth is... I'm a simple kind of idiot... I struggle with all the double negatives in Object.hashCode API. So here's my rewrite.
    The equals and hashCode methods share a special relationship.
    The general contract is:
    1. If two objects are equals they must have the same hashCode.
    2. BUT, If two objects have the same hashCode they don't necessarily have to be equals, but this is called "a hashCode clash", which ain't good. A poor hashCode implementation (one which produces a high proportion of "clashes") dramatically slows-down hashMap lookups. In hash-code-land: More distincter is more betterer.
    3. Both equals and hashCode must be consistent over time. The hashCode must remain unchanged unless an attribute effecting equals has changed... at which time the hashCode proabably should change (but see rule 2).
    The rules of thumb for developers are:
    1. The equals and the hashCode methods should examine the same attributes of the object.
    2. So... If you override hashCode you almost certainly need to override equals to fulfill the above contract.
    2. And vice versa: If you override equals you probably need to override hashCode to fulfill the above contract.
    And what the API should say but doesn't is that hashCode only affects Hash* collections (those which begin with the word "Hash") such as HashTable, and HashMap. If you're not using Hash* collections (and are positive that your objects will never be stored in a Hash* collection) then you can get away with totally ignoring hashCode and all of it's innate complexities; with the Caveat Emptor that surety is inversely proportional to the magnitude of the universe of discourse... so you're better off just doing it, coz it's easier than evaluating the consequences of NOT doing it.
    Just my two bobs worth.
    Cheers. Keith.

  • Why methods equals() and hashCode() is defined in Object Class?

    Why methods equals() and hashCode() is defined in Object Class?

    If you have two objects and you don't know (or care about) their exact types, but you still want to know if they are the same, then you can do something like this:
    Object o1 = getObject1();
    Object o2 = getObject2();
    if (o1.equals(o2)) {
      // they are the same, do something
    } else {
      // they are different, do something else
    }This could be useful if you were to write a generic cache, for example.
    A similar thing is true for hashCode(), if you want to manage things in a HashSet, you'll need them to implement hashCode().
    If Object didn't have those methods, then you'd have to write that code against a more specific interface/class and it wouldn't be so general any more.

  • HashSet get() and contains() methods, by value or reference?

    All the tutorials I've seen on HashSets use Strings as the object type. With Strings, it seems the get() and contains() methods work by value, not by reference.
    <CODE>
    String s1 = "dog";
    String s2 = "cat";
    String s3 = "dog";
    HashSet<String> set = new HashSet<String>();
    set.add(s1);
    System.out.println(set.contains(s1)); //true;
    System.out.println(set.contains(s2)); //false
    System.out.println(set.contains(s3)); //true
    </CODE>
    But when I use a custom object, it works by reference:
    <CODE>
    MyClass c1 = new MyClass("dog", 1);
    MyClass c2 = new MyClass("cat", 1);
    MyClass c3 = new MyClass("dog", 2);
    MyClass c4 = new MyClass("dog", 1);
    HashSet<MyClass> myClassSet = new HashSet<MyClass>();
    myClassSet.add(c1);
    System.out.println(myClassSet.contains(c1)); //true
    System.out.println(myClassSet.contains(c2)); //false
    System.out.println(myClassSet.contains(c3)); //false
    System.out.println(myClassSet.contains(c4)); //false
    </CODE>
    ("MyClass" is a simple class that holds a String and an int).
    Is there any way I can get the set to select by value rather than reference for objects that aren't String?
    If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?

    803559 wrote:
    With Strings, it seems the get() and contains() methods work by value, not by reference.
    String s1 = "dog";
    String s2 = "cat";
    String s3 = "dog";
    System.out.println(set.contains(s1)); //true;
    System.out.println(set.contains(s2)); //false
    System.out.println(set.contains(s3)); //true
    Is there any way I can get the set to select by value rather than reference for objects that aren't String?Warning: Never use the term "by reference" around Java geeks. It makes 'em go all green at the gills and they start muttering about 'bloody C++ crossovers'.
    However, as DrClap pointed out, you've mis-diagnosed the problem:
    System.out.println(s1 == s1);
    System.out.println(s1 == s2);
    System.out.println(s1 == s3));would print out the exact same results.
    For an explanation why, Google "Java String pool" or try [url http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal]here.
    If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?Absolutely. But, as others have said, you'd need to override equals() and hashCode().
    Winston

  • HashSet - equals and hashCode

    I must be missing the obvious over here..from what I understood of HashSet's/equals and hashCode, the program below should not add the Person object twice. Please suggest whats wrong...
    import java.util.*;
    public class TestHashSet2 {
    Set set = null;
    public TestHashSet2() {
    set = new HashSet();
    class Person {
    String name;
    Person(String name) {
    this.name = name;
    public boolean equals(Person person) {
    if (name.equals(person.name)) {
         return true;
    } else {
         return false;
    public int hashCode() {
    int code = name.length();
    System.out.println(" HashCode: " + code);
    return code;
    public void addPerson() {
    Person person1 = new Person("Mike");
    set.add(person1);
    Person person2 = new Person("Mike");
    System.out.println(" person1 equals person2: " + person1.equals(person2));
    set.add(person2);
    public void showPersons() {
    Iterator iterator = set.iterator();
    Object obj = null;
    while (iterator.hasNext()) {
    obj = iterator.next();
    System.out.println(" ELEMENT--> " + obj);
    System.out.println(" Number of elements in set: " + set.size());
    public static void main(String args[]) {
    TestHashSet2 tSet = new TestHashSet2();
    tSet.addPerson();
    tSet.showPersons();
    }

    the method equals(Person) has a different parameter type as equals(Object) and therefore doesn't override it. You need to change the method to equals(Object). This is a common 'gotcha' ...

  • HashCode() method and identityHashCode() difference

    Hi to All
    I am working in Java Strings. While studying java Strings, I am getting confusion to understand what is hashCode() and identityHashCode() method. I have written a small program and executed. I got two different out puts. Here i am posting my code.
    public class StringDemo {
         public static void main(String[] args){
              String str="Hello";
              System.out.println(str.hashCode());
              System.out.println(System.identityHashCode(str));     
    When i have run the above program i got the following out puts
    *69609650*
    *14978587*
    The first one is generated by hashCode() and second one is by identityHashCode(). Can any one explain me what are those two different nos. Thanks in advance.

    user10137999 wrote:
    The first one is generated by hashCode() and second one is by identityHashCode(). Can any one explain me what are those two different nos. Thanks in advance.You read the docs for Object.hashCode(), Object.identityHashCode(), and String.hashCode(), right? After reading those docs, what part did you not understand?

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

Maybe you are looking for

  • Safari Browser running very sluggishly or hanging since upgrading to Yosemite

    since upgrading my mac to yosemite my safari web browser is running painfully slow or it stops altogether. i have turned my router off and rebooted that and the mac but it still the same. any suggestions of what to do next please

  • IPhone 5

    Hello. I have a problem with activation my iPhone 5. I have bought the iPhone one month ago and update iOS 8.1.3 yesterday. After update iPhone has an activation screen and asks previous owner's Apple ID and Password. I don't know Apple ID and Passwo

  • HT2518 I don't have .psd files but how do I migrate my Photoshop Elements catalog with tags from Windows

    I don't have .psd files but how do I migrate my Photoshop Elements catalog with tags from Windows?

  • ZFS Dedup question

    Hello All, I have been playing around with ZFS dedup in Open Solaris. I would like to know how does ZFS store the dedup table. I know it is usually in memory, but it must leave a copy on disk. How is this table protected? Are their multiple copies li

  • IOS devices not recognizing a phone number as iMessage

    At some point my phone stopped recognizing the text conversation I have with my dad as iMessage. There are other conversation threads (with him and my stepmom, for instance) that are STILL in iMessage (in blue). For some reason though, the one I have