Intern
What is symmetry?
sobes.tech AI
Answer from AI
Symmetry in Java refers to the property of comparison relations (equals() and hashCode()) between objects. If a.equals(b) is true, then b.equals(a) should also be true. Violating this rule leads to unpredictable behavior in collections.
class MyObject {
private int value;
public MyObject(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyObject myObject = (MyObject) o;
return value == myObject.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
// Example demonstrating symmetry
MyObject obj1 = new MyObject(10);
MyObject obj2 = new MyObject(10);
// If obj1.equals(obj2) is true,
// then obj2.equals(obj1) should also be true.
boolean symmetric = obj1.equals(obj2) == obj2.equals(obj1);