在 Java 中将不可变实例分配给 Collection 的最佳方法
今天我在阅读一些 Hibernate 代码时遇到了一些有趣的事情。 有一个名为 CollectionHelper 的类,它定义了以下常量变量:
public final class CollectionHelper {
public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0 ) ;
public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection(new ArrayList(0) );
public static final Map EMPTY_MAP = Collections.unmodifiableMap( new HashMap(0) );
他们使用这些常量来初始化具有不可变实例的集合。为什么他们不简单地使用 Collections.EMPTY_LIST 来初始化列表?使用以下方法有好处吗?
Today I was reading through some Hibernate code and I encounter something interesting.
There is a class called CollectionHelper that defines the following constant varibale:
public final class CollectionHelper {
public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0 ) ;
public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection(new ArrayList(0) );
public static final Map EMPTY_MAP = Collections.unmodifiableMap( new HashMap(0) );
They have used these constants to initialize collections with immutable instances. Why they didn't simply use the Collections.EMPTY_LIST for initializing lists? Is there a benefit in using the following method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有任何好处。对我来说唯一明显的区别是,此方法保证返回与使用
Collections.emptyList()
创建的任何List
不同的EMPTY_LIST
,而Collections.emptyList()
的实现可能会也可能不会返回相同的List
实例。我更倾向于同意 @WizardOfOdds 的评论,他们根本不了解这些 API 函数。No, there is no benefit. The only difference apparent to me is that this method is guaranteed to return a different
EMPTY_LIST
than anyList
created withCollections.emptyList()
, whereas implemenations ofCollections.emptyList()
may or may not return the sameList
instances. I am more inclined to agree with @WizardOfOdds's comment that they simply didn't know about those API functions.有时,它可以通过减少特定调用站点使用的实现数量来提高性能,从而允许更好的单态和双态内联优化。不过,这个机会有点远。
The may be times when it improves performance by reducing the number of implementations used at a particular call-site, allowing better monomorphic and bimorphic inlining optimisations. Bit of a long shot, though.