开发者

The best way to assign an immutable instance to a Collection in Java

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 list开发者_高级运维s? Is there a benefit in using the following method?


No, there is no benefit. The only difference apparent to me is that this method is guaranteed to return a different EMPTY_LIST than any List created with Collections.emptyList(), whereas implemenations of Collections.emptyList() may or may not return the same List 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜