1

If I have this code:

public class Due {
    // TEST 3
    //Collection<Due> s = new HashSet<Due>();
    static Collection<Due> s = new HashSet<Due>();
    static int k,j;
    Due(int k, int j){
        this.k=k; this.j = j;
    }
    public boolean equals(Object d){
        return k-j==((Due)d).j - ((Due)d).k;
    }
    public int hashCode(){
        return 1;
    }
    public static void main(String[] args) {
        s.add(new Due(2,2));
        s.add(new Due(0,5));
        s.add(new Due(3,3));
        s.add(new Due(5,0));
        System.out.println(s.size());
        for(Due x:s){System.out.println(x.k + " "+x.j);}
    }    
}

Every time I insert an object to the HashSet, does it call equals() and HashCode() in order to determine whether it has or not the element inside already? In this case s.add(new Due(0,5)); is equal to s.add(new Due(5,0)); ? What happen if there are no defined equals() and hashCode() ?

bog
  • 1,323
  • 5
  • 22
  • 34
  • see here: http://stackoverflow.com/a/27609/3887073 – Ben Aug 31 '14 at 09:22
  • 1
    Short answer is yes (I had a longer answer, but sadly this has been closed)... so you should fix equals() to actually check the type on the right-hand side, fix hashCode() to use the fields to compute a hash (rather than returning a constant), and also fix "k" and "j" to be non-static (since you seem to want these to differ for each instance). – Michael Aaron Safyan Aug 31 '14 at 09:27
  • By the way, you equals method compares k-j on the left with j-k on the right. – Florian F Aug 31 '14 at 09:39
  • hashCode() is called every time but equals() is called if collision occured. – mirmdasif Aug 31 '14 at 09:42
  • Every time you override equals() you should override hashCode() as well. These two methods must return the same result. So if equals says that two objects are equal they need to have the same hashcode. You need this to make sure that your objects work with all the "Hash" stuff in Java like HashSet, HashMap and so on. Overriding hashcode can be a bit hard. So if you just want to compare two objects make your own method which not overrides equals(). – Lars Aug 31 '14 at 10:17

0 Answers0