首页 > 解决方案 > 如何维护不可变类中的可变对象列表

问题描述

我有 Immutable 类,其中有 Mutable 类对象的列表。

class Immutable
{
    final int id;
    final String name;
    final List<Mutable> list;
    Immutable(int id,String name,List<Mutable> list)
    {
        this.id=id;
        this.name=name;
        this.list=list;
    }

    public List<Mutable> getMutables()
    {
        List<Mutable> l=new ArrayList<>(this.list);
        return l;
    }

}

class Mutable
{
    String name;
    Mutable(String name)
    {
        this.name=name;
    }
}

在这里,我的 getMutables 方法是创建对象并返回克隆的对象。但是如果有这么多线程或请求访问 getMutables 方法,那么它最终会创建多个对象,很快就会出现内存不足的错误。

在 getMutables 方法中做什么,这样原始对象就不会被修改,并且不会创建更多对象。

请帮忙

标签: multithreadingconcurrencyimmutabilitycoremutable

解决方案


Instead of returning new ArrayList in getMutables(), we can return unmodifibleList of Mutable objects from getMutables(). 

public List<Mutable> getMutables()
    {
        return Collections.unmodifiableList(this.list);
    }

The unmodifiable Collection method of Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections.

Collections.unmodifiableList(mutableList);
Collections.unmodifiableSet(mutableSet);
Collections.unmodifiableMap(mutableMap);

推荐阅读