class DataKey { private int id; DataKey(int id) { this.id = id; }}public class MyClass { public static void main(String[] args) { Map<DataKey, String> hm = new HashMap<>(); hm.put(new DataKey(1), "Chintoo"); hm.put(new DataKey(1), "Chintoo"); System.out.println(hm.size()); // this will print 2 // also now it is impossible to find out // the hashmap value by key }}
It is also related to hash collisions and distribution of Keys
For two entries in hash table: (Each entry = {Obj, Val})
If they have same hashCode() but different equals(), then HashTable will insert into linked list for the same hashCode()
If they have different hashCode(), then HashTable will insert into different bucket
HashTable: [X0, X1, X2, ....] -- bucketsEach Key in HashTable point to linked listX0 --> [ {Obj1, Val1} --> {Obj2, Val2} ]X1 --> [ {Obj3, Val3} ]From the above, we can see:Obj1.hashCode() == Obj2.hashCode() # possible to have collisionObj1.equals(Obj2) == falseObj1.hashCode() != Obj3.hashCode()which also implies Obj1.equals(Obj2) is false
clone()
Following is taken from JDK 17
It is implemented using native, hence implementation is internal
If the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown when calling this method
Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment.
Hence, This method performs a “shallow copy” of this object, not a “deep copy” operation.
A class that implements the Cloneable interface is expected to override the Object.clone() method to provide a public clone method since it is protected method and cannot be used anywhere else
class MyClass implements Cloneable { @Override public Object clone() throws CloneNotSupportedException { return super.clone(); }}// without Cloneable implementationclass MyClass2 { @Override public Object clone() throws CloneNotSupportedException { return super.clone(); }}public static void main(String... args) { MyClass obj = new MyClass(); MyClass clonedObj = (MyClass) obj.clone(); MyClass2 obj2 = new MyClass2(); // throws CloneNotSupportedException MyClass2 clonedObj2 = (MyClass2) obj2.clone(); }
It is not recommended to use Cloneable cloning feature, instead use: