Java:没有来自外部类的ArrayList修改(Java: No ArrayList modifications from outside classes)

编程入门 行业动态 更新时间:2024-10-27 13:25:50
Java:没有来自外部类的ArrayList修改(Java: No ArrayList modifications from outside classes)

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

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

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

I use an ArrayList in one of my Java project's classes. The class keeps track whether the list has been changed and offeres a couple of public methods to add and remove elements from the list that automatically set the variable to "changed".

So far the list is public because I want my list to be publicly readable from everywhere. But I only want the class that owns the list to be able to modify it. So no modifications from outside classes. Is that possible? If so, how?

Usually for access control you'd, probably use getter and setter methods. But even with a getter method and the list set to private another class could still do getList().remove(element) and thereby modify the list from the outside without the class noticing that the list was changed.

最满意答案

使您的ArrayList字段为私有,但让您的getter返回Collections.unmodifiableList(list) ,它提供了一个不可修改的视图。

这将允许外部代码将其视为普通List,用于每个循环等,但将禁用修改操作。 此外,unmodifiableList以恒定时间返回视图。

这实际上就是它的设计用例。 的Javadoc:

此方法允许模块为用户提供对内部列表的“只读”访问。 对返回列表的查询操作“读取”到指定列表,并尝试修改返回的列表,无论是直接还是通过其迭代器,都会导致UnsupportedOperationException。

Make your ArrayList field private, but have your getter return Collections.unmodifiableList(list), which provides an unmodifiable view.

This will allow external code to treat it as a normal List, using for each loops and so on, but will disable modification operations. Additionally, unmodifiableList returns a view in constant time.

This is literally the exact use case it was designed for. Javadoc:

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.

更多推荐

本文发布于:2023-07-22 19:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ArrayList   Java   classes   modifications

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!