What I am trying to do here is to fill a HashMap
with objects Obj
using the key Key
and when I finish I want to have access to those values according to any any of the possible keys. I have written the following code and what happened is that although the first show really shows the values I want, the second one raises a NullPointerException
.
import java.util.*;
public class My{
public static void main(String[] args){
Map<Key,Obj> myMap = new HashMap<Key,Obj>();
Obj ob1 = new Obj("Nick",19);
Obj ob2 = new Obj("George",17);
Key key1 = new Key(1,2);
Key key2 = new Key(2,1);
myMap.put(key1,ob1);
myMap.put(key2,ob2);
myMap.get(key1).show();
myMap.get(new Key(1,2)).show();
}
I can tell that somehow Java cannot tell that new Key(1,2)
is equal with key1
, but I cannot think of how can I overcome this issue.
public class Obj{
private String name;
private int age;
Obj(String name, int age){
this.name = name;
this.age = age;
}
public void show(){
System.out.println(name + " " + age);
}
}
These are the classes I use
import java.* ;
public class Key{
public int x,y;
Key(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Key d){
if ((this.x == d.x)&&(this.y == d.y)){
return true;
}
else{
return false;
}
}
}