【问题标题】:java: how do I stop people from clearing my arraylist<string> When I use a getter method?java:当我使用getter方法时,如何阻止人们清除我的arraylist<string>?
【发布时间】:2014-04-21 19:34:04
【问题描述】:

我已经在 A 类中声明了我的数组列表:

private ArrayList<String> user = new ArrayList<String>();

我在同一个类(A 类)中创建了我的 getter 方法:

public ArrayList<String> getUser()
{
return user;
}

然后在我的第二堂课(B 类)中,我能够做到以下几点:

A UD = new A();
UD.getUser().clear();
UD.getErrmsg().clear();

如何防止我的第二个班级清除我的第一个班级(A 级)中的数组列表?

【问题讨论】:

  • Collections.unmodifiableList(list).
  • 已经说过两次了,或者使用 Guava 及其ImmutableList;但是,这并不能阻止 setter 问题的发生
  • 您需要制作所谓的防御性副本。检查这个问题stackoverflow.com/questions/9743513/…。之前的建议准确地提到了这是如何完成的
  • 感谢帮了大忙的人。

标签: java generics arraylist


【解决方案1】:

Collections 类中有一个方法可以使用:return Collections.unmodifiableList(user); 您可能还需要各种其他方法,包括用于地图的方法等等。看看documentation吧。

【讨论】:

    【解决方案2】:

    getter setter 的解决方案:

    public void setMyList(final List<String> list)
    {
        myList = new ArrayList<>(list);
    }
    
    public List<String> getMyList()
    {
        return Collections.unmodifiableList(list);
    }
    

    使用番石榴:

    public void setMyList(final List<String> list)
    {
        myList = ImmutableList.copyOf(list);
    }
    
    public List<String> getMyList()
    {
        return list;
    }
    

    如果你负担得起,请使用番石榴。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 2022-01-14
      • 2016-10-05
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多