Java Reference
In-Depth Information
if (obj instanceof BadKey) {
BadKey bk = (BadKey) obj;
if (bk.getId() == this.id) {
return true;
}
}
return false;
}
@Override
public String toString() {
return String.valueOf(this.id);
}
}
The
BadKey
class stores an integer value. It is a mutable class. You can modify its state by calling the
setId()
method and supplying a new value for its
id
. It overrides the
equals()
and
hashCode()
methods of the
Object
class.
The implementation of the
hashCode()
method is simple. It returns the value of the
id
instance variable as the hash
code value. The
equals()
method checks if the
id
instance variable's value for two
BadKey
objects are the same or not.
If two
BadKey
objects have the same
id
, they are considered equal.
Consider the program in Listing 12-35 that uses
BadKey
objects in a
Set
. Can you spot a problem by looking at the
program and the output? Don't worry if you do not see the problem. I will explain it.
Listing 12-35.
Using BadKey Objects in a Set
// BadKeyTest.java
package com.jdojo.collections;
import java.util.HashSet;
import java.util.Set;
public class BadKeyTest {
public static void main(String[] args) {
Set<BadKey> s = new HashSet<>();
BadKey bk1 = new BadKey(100);
BadKey bk2 = new BadKey(200);
// Add two objects bk1 and bk2 to the set
s.add(bk1);
s.add(bk2);
System.out.println("Set contains:" + s);
System.out.println("Set contains bk1: " + s.contains(bk1));
// Set the id for bk1 to 300
bk1.setId(300);
System.out.println("Set contains:" + s);
System.out.println("Set contains bk1: " + s.contains(bk1));
}
}