Collections.emptyMap() vs new HashMap()

前端 未结 9 591
南旧
南旧 2020-12-22 21:22

What are some of the situations where I can use Collections.emptyMap() ? The Documentation says I can use this method if I want my collection to be immutable. <

9条回答
  •  春和景丽
    2020-12-22 22:06

    It is, in my personal experience admittedly, very useful in cases where an API requires a collection of parameters, but you have nothing to provide. For example you may have an API that looks something like this, and does not allow null references:

    public ResultSet executeQuery(String query, Map queryParameters);
    

    If you have a query that doesn't take any parameters, it's certainly a bit wasteful to create a HashMap, which involves allocating an array, when you could just pass in the 'Empty Map' which is effectively a constant, the way it's implemented in java.util.Collections.

提交回复
热议问题