HashMap output based interview question
I love learning about technology and sharing that with others
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String args[]) {
Person p1 = new Person("Ramesh", 30);
Person p2 = new Person("Sathish", 31);
Person p3 = new Person("Sathish", 31);
Person p4 = p1;
Map<Person,Integer> map=new HashMap<>();
map.put(p1,1);
map.put(p2,2);
// when we put something in the map which is not already there that time it will return null
System.err.println(map.put(p3,3)); // print null
// when we inject something which is already there map will return its value other wise nulll
System.err.println(map.put(p4,4));
System.out.println(map.size()); // size 3 -> since p4 is not injected :)
map.forEach((k,v) -> System.err.println(k+" "+v));
}
}
class Person {
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
@Override
public String toString() {
return this.name;
}
}

