waltermilner

Untitled

Nov 1st, 2019
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.66 KB | None | 0 0
  1. import java.util.HashMap;
  2.  
  3. // Using HashMap
  4. // with a key with no hashCode or equals over-riding
  5. public class Test {
  6.  
  7.   public static void main(String[] args) {
  8.     HashMap<MyClass, String> map = new HashMap<>();
  9.     MyClass a = new MyClass(1);
  10.     MyClass b = new MyClass(2);
  11.     MyClass c = new MyClass(3);
  12.     map.put(a, "One");
  13.     map.put(b, "Two");
  14.     map.put(c, "Three");
  15.     String str = map.get(a);
  16.     System.out.println(str); // One
  17.     map.put(b, "Change"); // update value of key b
  18.     str = map.get(b);
  19.     System.out.println(str); // Change
  20.   }
  21. }
  22.  
  23. class MyClass // key class
  24. {
  25.  
  26.   int x;
  27.  
  28.   MyClass(int x) {
  29.     this.x = x;
  30.   }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment