gpt4 book ai didi

Java:没有来自外部类的 ArrayList 修改

转载 作者:搜寻专家 更新时间:2023-11-01 02:24:47 25 4
gpt4 key购买 nike

我在我的一个 Java 项目的类中使用了 ArrayList。该类跟踪列表是否已更改,并提供公共(public)方法来添加和删除自动将变量设置为“已更改”的列表中的元素。

到目前为止,该列表是公开的,因为我希望我的列表可以从任何地方公开读取。但我只希望拥有列表的类能够修改它。所以没有来自外部类的修改。那可能吗?如果是,怎么办?

通常对于访问控制,您可能会使用 getter 和 setter 方法。但即使使用 getter 方法并将列表设置为私有(private),另一个类仍然可以执行 getList().remove(element) 并因此从外部修改列表,而类不会注意到列表已更改。

最佳答案

将您的 ArrayList 字段设为私有(private),但让您的 getter 返回 Collections.unmodifiableList(list),这提供了一个不可修改的 View 。

这将允许外部代码将其视为普通列表,使用 for each 循环等,但会禁用修改操作。此外,unmodifiableList 在恒定时间内返回一个 View 。

这正是它设计的确切用例。 Java文档:

This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

关于Java:没有来自外部类的 ArrayList 修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27635637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com