Search code examples
javastatichashmap

Why does static hashmap created for every instances?


I have a course class having one Hashmap. I'm trying to add values to the map with different objects. Map is common for all the objects so I marked it as Static still it shows weird behavior. I have the following code -

class Course
{
    static HashMap<Integer,List<String>> map;
    Course()
    {
        map = new HashMap<>();
    }
    public boolean add(int id,String Course)
    {
        if(!map.containsKey(id))
        {
            map.put(id,new ArrayList<>());
        }
        try 
        {
            List<String> temp = map.get(id);
            temp.add(Course);
            return true;        
        } catch (Exception e) 
        {   
            return false;
        }        
    }
    public void get()
    {
        System.out.println(map);
    }

    public static void main(String[] args)
    {
        Course c = new Course();
        c.add(1, "abs");
        c.add(2,"xyx");
        c.add(1,"new");
        c.add(3,"tye");
        c.get();
        Course c2  = new Course();
        c2.add(1,"GP");
        c2.add(2, "PT");
        c2.get();

    }   
}

I have defined Hashmap as static because it is common for all the objects. But still, the new Hashmap is created for every instance.

Output

{1=[abs, new], 2=[xyx], 3=[tye]}
{1=[GP], 2=[PT]}

Solution

  • Because you initialize it in the constructor.

    Don't. Just initialize it on the field:

    static HashMap<Integer,List<String>> map = new HashMap<>();
    

    (And remove the constructor).

    And consider making the field final if you never intend to reassign it. This ensures that 1) you don't actually reassign it; 2) you actually do assign it once.