Question from the interview. No more data. What should Action.f3() return? Offer another implementation of the Map with the same behavior. For some reason, my method returned null .

Action.class

 public class Action { public static Object f3() { Map map = new HashMap(20); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); Map myMap = new MyMap(map); return myMap.get("1"); } } 

MyMap.class

 class MyMap implements Map { private Map anotherMap; public MyMap(Map anotherMap) { this.anotherMap = anotherMap; } public boolean containsKey(Object key) { // ..... } public Object get(Object key) { Iterator it = anotherMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); if (key.equals(e.getValue())) { return e.getKey(); } } return null; } public int size() { //.... } //... } 
  • one
    Well, logically, the expected behavior is to return One . We create our own myMap implementation myMap passing another Map to the constructor, sort of like we need to copy all the fields. And the question is what? And to be honest, some strange method get in map take an element for O(n) if any map not worse than O(log N) it does ... - pavel
  • one
    null you because you are null and return -> return null; in other words, everything works for you - Peter Slusar
  • one
    you are definitely not confused in the get method where is the key and where is the value used? - pavel
  • Copied from the job one to one. In what a dirty trick of a question did not understand yet, I try to understand. - Alexander Dermenzhi
  • one
    The task seems to be purely on checking your attentiveness - iksuy

2 answers 2

 Map.Entry e = (Map.Entry) it.next(); if (key.equals(e.getValue())) ^^^ Вы сравниваете ключ с значением. { return e.getKey(); } 

    That's right, the above code will return null .
    Take a closer look at the implementation of the get method in MyMap , or rather on the condition in if . There you compare the argument passed in get to the entry value (you compare "1" with "One" , "Two" , "Three" ). Naturally there are no matches, and, having passed a cycle over all entry , falls on return null .