Wrapper Comparison, Equality, and Hash Code
Each wrapper class implements the Comparable<Type> interface, which defines the following method:
int compareTo(
Type
obj2)
This method returns a value that is less than, equal to, or greater than zero, depending on whether the primitive value in the current wrapper Type object is less than, equal to, or greater than the primitive value in the wrapper Type object denoted by argument obj2, respectively.
// Comparisons based on objects created earlier
Character charObj2 = ‘a’;
int result1 = charObj1.compareTo(charObj2); // result1 < 0
int result2 = intObj1.compareTo(intObj3); // result2 > 0
int result3 = doubleObj1.compareTo(doubleObj2); // result3 == 0
int result4 = doubleObj1.compareTo(intObj1); // Compile-time error!
Each wrapper class overrides the equals() method from the Object class. The overriding method compares two wrapper objects for object value equality.
boolean equals(Object obj2)
// Comparisons based on objects created earlier
boolean charTest = charObj1.equals(charObj2); // false
boolean boolTest = boolObj2.equals(Boolean.FALSE); // false
boolean intTest = intObj1.equals(intObj3); // true
boolean doubleTest = doubleObj1.equals(doubleObj2); // true
boolean test = intObj1.equals(Long.valueOf(2020L)); // false. Not same type.
The following values are interned when they are wrapped during boxing. That is, only one wrapper object exists in the program for these primitive values when boxing is applied:
- The boolean value true or false
- A byte
- A char with a Unicode value in the interval [\u0000, \u007f] (i.e., decimal interval [0, 127])
- An int or short value in the interval [-128, 127]
If references w1 and w2 refer to two wrapper objects that box the same value, which fulfills any of the conditions mentioned above, then w1 == w2 is always true. In other words, for the values listed previously, object equality and reference equality give the same result.
// Reference and object equality
Byte bRef1 = 10;
Byte bRef2 = 10;
System.out.println(bRef1 == bRef2); // true
System.out.println(bRef1.equals(bRef2)); // true
Integer iRef1 = 1000;
Integer iRef2 = 1000;
System.out.println(iRef1 == iRef2); // false, values not in [-128, 127]
System.out.println(iRef1.equals(iRef2)); // true
Each wrapper class also overrides the hashCode() method in the Object class. The overriding method returns a hash value based on the primitive value in the wrapper object.
int hashCode()
int index = charObj1.hashCode(); // 10 (‘\n’)
Leave a Reply