Well my code works, but I just can't understand why a private
variable works in this case, inside function equals()
.
Or is it just a trick that if you call another object from inside the same kind of object structure then the private
identifier doesn't count?
public class TestClass implements Comparable <TestClass> {
private final String name;
public TestClass(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TestClass) {
return ((TestClass) obj).name.equals(name); //<- how does this work, isn't name private?
} else {
return false;
}
}
@Override
public int compareTo(TestClass test) {
int thisValue = hashCode();
int otherValue = test.hashCode();
if (thisValue < otherValue) {
return -1;
} else if (thisValue > otherValue) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return name;
}
}