HashMaps中类的多个对象

时间:2015-11-12 14:08:43

标签: java class object hashmap

我在创建B类对象时遇到问题,所有对象都应该是分开的。但是当我对其中一个对象进行更改时,所有对象都会进行相同的更改。应如何实践?这是一个示例代码:

CLASS A:

public class A {

    private static HashMap<String, B> map = new HashMap<String, B>();
        public void newObject (String name) {
            if (map.containsKey(name)) {

        } else {
            Person person = new Person (name);

            map.put(name, person);

        }
    }

    //This method gets called several times, to create several objects

    //But it everytime i create a new object, all the old/existing objects change too.


}

CLASS Person:

public class Person {
    private static String name;

    public Person (String name) {
        this.name = name;
    }

}

1 个答案:

答案 0 :(得分:3)

name中的Person从静态变为私有(将其作为成员变量)。