This question already has answers here:
Immutable class?
                                
                                    (9个答案)
                                
                        
                                2年前关闭。
            
                    
public final class Multi {
    private final String name;
    private final int number;
    private final ArrayList<String> otherNames;

    Multi(String name, int number) {
        this.name = name;
        this.number = number;
        this.otherNames = new ArrayList<String>();
    }

    public void addOtherNames(String name) {
        this.otherNames.add(name);
    }


    // All getter methods should be a copy of the class fields
    public ArrayList<String> getOtherNames() {
        return new ArrayList<String>(otherNames);
    }
}


当涉及数据结构(例如ArrayList ect)时,我很难理解不变性。

当我有诸如addOtherNames之类的方法时,它将在对象创建后将内容添加到列表中。

谢谢

最佳答案

从技术上讲,它是不可变的。

但是您不能通过它到达的对象(otherNames)不是,因此它不是线程安全的。

关于java - 此类是不可变的吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45990901/

10-09 00:17