[英]Why are the Unmodifiable collections protected to the Collections package?
I cannot fathom why Java wishes to hide immutable unmodifiable collections from being passed around. 我无法理解为什么Java希望隐藏
不可变的,不可修改的集合,以免被传递出去。
It makes life harder on devs because you can't guarantee that a class is returning anything immutable unmodifiable, forcing you to smatter calls to Collections.unmodifiableWhatever throughout your code. 这使开发人员的工作更加困难,因为您不能保证类返回的是
不可修改的不可变内容 ,从而迫使您将对Collections.unmodifiable的调用分散到整个代码中。 This is both wasteful and annoying. 这既浪费又烦人。
Is there a reason I'm missing behind why you would make these methods protected, or another library I'm missing that contains public versions of immutable and/or unmodifiable collections? 是否有我为什么要保护这些方法的原因,还是我缺少另一个包含不可变和/或不可修改集合的公共版本的库?
For the purposes of learning more about java, let's say Scala does not count as an answer to "a library that contains public versions of immutable collections" :) 为了更多地了解Java,假设Scala不算是“包含不可变集合的公共版本的库”的答案:)
I think it has to do with the design goals of the framework: 我认为这与框架的设计目标有关:
The main design goal was to produce an API that was small in size and, more importantly, in "conceptual weight."
主要设计目标是生产一种尺寸更小且更重要的是“概念重量”的API。
You should check out Guava's immutable collection types , if you are willing to learn more conceptual weight :) 如果您想了解更多概念上的分量,则应该查看Guava的不可变集合类型 :)
The Collections
interface permits one to wrap an exiting Collection
so that calls to mutator methods result in failure. Collections
接口允许包装一个退出的Collection
这样对mutator方法的调用会导致失败。
unmodifiableCollection(Collection c) : "Returns an unmodifiable view of the specified collection." “ unmodifiableCollection(Collection c) :”返回指定集合的不可修改视图。
It makes life harder on devs because you can't guarantee that a class is returning anything immutable, ... This is both wasteful and annoying. 这使开发人员的生活更加艰苦,因为您不能保证一个类返回的是不可变的东西,这既浪费又烦人。
The JDK source of the Collections.unmodifiableList()
method is: Collections.unmodifiableList()
方法的JDK源是:
public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<>(list) :
new UnmodifiableList<>(list));
}
I see why this can be considered wasteful (these generics also make it ugly). 我知道为什么这可以被认为是浪费的(这些泛型也使它变得难看)。 Why doesn't that method check whether the passed instance is already an
UnmodifiableRandomAccessList
or UnmodifiableList
? 该方法为什么不检查传递的实例是否已经是
UnmodifiableRandomAccessList
或UnmodifiableList
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.