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()
?