番石榴:ImmutableList.of(E[]) 的最佳实践
我刚刚注意到 ImmutableList.of(E[])
已弃用,取而代之ImmutableList.copyOf()
,显而易见的原因是,如果原始数组在其他地方使用,则列表不能真正变得不可变。
如果您有一个返回数组的方法,并且您知道该方法不保留对数组的引用,并且您的代码除了将其传递给 < 之外,也不保留对数组的引用,该怎么办?代码>ImmutableList.of()?
我应该...
- 继续使用
ImmutableList.of(E[])
(似乎是一个坏主意,因为该方法将消失) - 使用
Collections.unmodifyingList(Arrays.asList())
- 使用
ImmutableList.copyOf()
——这似乎是不会出现性能/资源问题的最佳主意,否则复制是不必要的。
I just noticed that ImmutableList.of(E[])
is deprecated in favor of ImmutableList.copyOf()
, for the obvious reason that the list can't truly be made immutable if the raw array is used elsewhere.
What if you have a method that returns an array, and you know for a fact that the method doesn't hold onto a reference to the array, and your code doesn't hold onto a reference to the array other than passing it to ImmutableList.of()
?
Should I...
- continue to use
ImmutableList.of(E[])
(seems like a bad idea since the method will go away) - use
Collections.unmodifiableList(Arrays.asList())
- use
ImmutableList.copyOf()
-- this seems like the best idea where performance/resource issues don't arise, otherwise the copy is unnecessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ImmutableList.of(E[])
没有也从未存储过直接给定的数组(如果这样做的话它也不是不可变的,这会破坏类的要点)。由于命名原因,它已被弃用。如果你看一下实现,就会发现:所以我的建议是一般只使用
ImmutableList.copyOf()
。如果您知道您只是包装一个数组以供内部使用或类似的用途,请随意保存副本并仅使用 Arrays.asList ,但我更喜欢 ImmutableList对于 API。ImmutableList.of(E[])
does not and has never stored the array it's given directly (it wouldn't be immutable if it did, which would defeat the point of the class). It was deprecated for naming reasons. If you take a look at the implementation, it is:So my advice would be to just use
ImmutableList.copyOf()
in general. If you know you're just wrapping an array for internal use or some such, feel free to save yourself the copy and just useArrays.asList
but I'd preferImmutableList
for the API.