4 Replies Latest reply: Jun 25, 2010 10:35 PM by EJP RSS

    HashSet is not working

    843793
      I have a code:

      Test.java
      ########
      package p1;
      public class Test{
           int t;
           @Override
           public boolean equals(Object v1){
                if(((Test)v1).t==t)
                     return true;
                else
                     return false;
           }
           public Test(int c){
                t=c;
           }
      }

      Collect.java
      ##########
      import java.util.*;
      import p1.*;
      public class Collect
      {
           public static void main(String args[])
           {
                HashSet hs=new HashSet();
                hs.add(new Test(10));
                hs.add(new Test(10));
                System.out.println(hs.size());
           }
      }

      #############################################
      Why not second object of Test is discarded, as Set allows unique elements.
        • 1. Re: HashSet is not working
          843793
          The HashSet use the Object of Test's hashCode method to judge the objects whether or not same.

          to write follow code:
           class Test{
               private int i;
               public Test(int t) {
                    this.i=t;
               }
               @Override
               public int hashCode() {
                    return i;
               }
          }
           System.out.println(set.size());//~  1
          print 1.
          • 2. Re: HashSet is not working
            843793
            ivanzhangwb wrote:
            The HashSet use the Object of Test's hashCode method to judge the objects whether or not same.
            Well, it checks the hash code first, but it also uses equals(). If two objects are equal according to the equals() method, they must have the same hash code.
            class Test{
                private int i;
                public Test(int t) {
                    this.i=t;
                }
            
                @Override
                public int hashCode() {
                    return i;
                }
            
                @Override
                public boolean equals(Object other) {
                    return (other instanceof Test && ((Test)other).i == this.i);
                }   
            }
            • 3. Re: HashSet is not working
              843793
              Thanks,
              It checks both methods Sequentially.
              • 4. Re: HashSet is not working
                EJP
                It tests the hash codes first. If they are equal it then calls equals().