Good day. I try to learn associative arrays. Available: UPD

import java.util.*; class Map { int a; String value; String key; HashMap<String, String> map; Map(){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); } int getSize(){ return map.size(); } String getValue(String key) { this.key = key; return map.get(key); } } public class Pr10_2 { public static void main(String[] args) { Map mp = new Map(); System.out.println(mp.getSize()); System.out.println(mp.getValue("key1")); } } 

I'm trying to get the value of key1 value getValue method, but the editor emphasizes the map in the line return map.get(key); . It was the same with getSize() , I had to do it differently. Can you please tell me, can I somehow incorrectly request the value? Or announce something wrong?

    2 answers 2

    I would rewrite the class like this:

     class Map { HashMap<String, String> map; Map(){ map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); } int getSize(){ return map.size(); } String getValue(String key) { return map.get(key); } } 
    • Yes you are right. It turns out in that code I declared map second time and accordingly received NPE. Thank you) - Pollux

    The problem is that the map variable from the getValue method getValue not visible

     class Map { int a; String value; String key; HashMap<String, String> map; Map(){ map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); a = map.size(); } int getSize(){ return a; } String getValue(String key) { this.key = key; return map.get(key); } } 

    Try this

    • Thanks, the map has become available, although now for some reason, even on the return map.size(); I get NPE - Pollux