Java Class 线程安全集合不可变

Java Class Immutable with Thread Safe Collection

假设我有以下 class:

public final class Person {

   final private String personFirstName;
   final private String personLastName;
   final private ConcurrentMap<Double, String> phoneMessages;

    public Person(String firstname, String lastname) {
       phoneMessages = new ConcurrentHashMap<Double, String>();
       this.personFirstName = firstname;
       this.personLastName = lastname;
    }

    public void add(Double key, String item) {
        phoneMessages.put(key, item);
    }

    public String getPersonFirstName() {
        return personFirstName;
    }

    public String getPersonLastName() {
        return personLastName;
    }

}

即使我创建了一个带有私有最终线程安全集合的 class,我的 class 是不可变的吗?我的猜测是没有。

如果在对象中使用集合不是正确的做法,那么 Java 中的正确做法是什么?我将如何着手设计包含集合的 class?

正如其他人所指出的,如何 使用您的 class 将决定使其不可变是否合适。

也就是说,您的 Person class 的这个版本是不可变的:

public final class Person {

   final private  String personFirstName;
   final private  String personLastName;
   final private ConcurrentMap<Double,String> phoneMessages;

    public Person(String firstname, String lastname) {
       this.phoneMessages = new ConcurrentHashMap<Double,String> ();
       this.personFirstName = firstname;
       this.personLastName  = lastname;
    }

    private Person(String firstname, String lastname, ConcurrentHashMap<Double,String> phoneMessages) {
       this.personFirstName = firstname;
       this.personLastName  = lastname;
       this.phoneMessages = phoneMessages;
    }

    public Person add(Double Key, String item){
        ConcurrentHashMap<Double, String> newMap = new ConcurrentHashMap<>(this.phoneMessages);
        newMap.put(Key, item);
        return new Person(this.personFirstName, this.personLastName, newMap);
    }

    public String getPersonFirstName() {
        return personFirstName;
    }

    public String getPersonLastName() {
        return personLastName;
    }

    public Map<Double, String> getPhoneMessages() {
        return Collections.unmodifiableMap(this.phoneMessages);
    }

}

请注意 add 方法 returns 是 Person 的不同实例,因此当前 Person 实例保持不变(不可变)。