开发者

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

开发者 https://www.devze.com 2022-12-28 17:10 出处:网络
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:

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

精彩评论

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

关注公众号