There was a need to create a dictionary class, the method of which for each word returns its text explanation. Initialize the dictionary with several words.
In this case, always returns null . What have I done wrong?

 pulic class Dict extends HashMap { HashMap<String, String> dict = new HashMap<String, String>(); String first; String second; public Dict(String first, String second) { dict.put(first, second); } public Dict() {} public void put(String first, String second) { dict.put(first, second); } public void printDict(String first) { System.out.println(dict.get(this.first)); } } 

Main:

 public class Main { public static void main(String[] args) { Dict dict = new Dict(); dict.put("я", "мы"); dict.put("ты", "вы"); dict.put("он, она, оно", "они"); dict.printDict("я"); } } 
  • one
    Write HashMap<String, String> dict = new HashMap<String, String>(); By the way, you can shorten it to HashMap<String, String> dict = new HashMap<>(); . - Regent
  • Another point: using both extends HashMap and HashMap<String, String> dict very strange. If you do not need Dict to be able to do everything the same as HashMap , then extends HashMap should be removed. - Regent
  • @Regent, But what if a person uses java 6 ??? - Bohdan Korinnyi
  • @BogdanK and what does it affect in this case? Or are you talking about the first commentary and the diamond operator? - Regent
  • @Regent, I'm talking about diamond - Bohdan Korinnyi

1 answer 1

I do not know why you need the first and second fields, because they are not used in any way.
The printDict method should have dict.get(first) : it makes sense to use the parameter passed to the method instead of the unused and uninitialized field.

 public void printDict(String first) { System.out.println(dict.get(first)); }