简体   繁体   English

为什么要为每个实例创建 static hashmap?

[英]Why does static hashmap created for every instances?

I have a course class having one Hashmap .我有一门课程 class 有一个Hashmap I'm trying to add values to the map with different objects.我正在尝试使用不同的对象向 map 添加值。 Map is common for all the objects so I marked it as Static still it shows weird behavior. Map 对所有对象都很常见,所以我将其标记为 Static 仍然显示出奇怪的行为。 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.我已将Hashmap定义为 static,因为它对所有对象都是通用的。 But still, the new Hashmap is created for every instance.但是,仍然会为每个实例创建新的Hashmap

Output Output

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

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.如果您从不打算重新分配该字段,请考虑将其设为final字段。 This ensures that 1) you don't actually reassign it;这可以确保 1) 您实际上不会重新分配它; 2) you actually do assign it once. 2)您实际上确实分配了一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM