telendri telendri - 4 years ago 150
Java Question

Influence of HashCode and equals on object's instanciation

I made some tests regarding methods. I came across a case that baffles me completely. Here's an example.

public abstract class Ge {

private boolean valid;

public Ge(boolean valid) {
this.valid = valid;
}

@Override
public int hashCode() {
return this.getClass().getSimpleName().hashCode();
}

@Override
public boolean equals(Object obj) {
if (getClass() == obj.getClass())
return true;
return false;
}
}

public class Ge1 extends Ge{

public Ge1(boolean valid) {
super(valid);
}
}

public class Ge1 extends Ge{

public Ge1(boolean valid) {
super(valid);
}
}

public class Ge2 extends Ge{

public Ge2(boolean valid) {
super(valid);
}
}


The test class:

public static void main(String args[]){
Ge1 ge1=new Ge1(true);
System.out.println(Integer.toHexString(System.identityHashCode(ge1)));
Ge1 ge11=new Ge1(false);
System.out.println(Integer.toHexString(System.identityHashCode(ge11)));
}


Although, the values of System.identityHashCode are different in the eclipse console, the ge1 and ge11 variable in debug mode have the same reference.

However, if I delete the hashcode and equals in class Ge, ge1 and ge11 have different references.

I do not understand why ge1 and ge11 have the same reference with hashcode and equals?

1

Answer Source

Object's toString() method is documented as

this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Your algorithm gives the same hashCode to all instances of Ge1.

So all the instances of Ge1 also have the same value returned by toString(), and displayed by Eclipse.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download