Why initialize HashSet<>(0) to zero?

前端 未结 5 1153
半阙折子戏
半阙折子戏 2021-02-07 02:50

I love a HashSet<>() and use this eagerly while initializing this with the default constructor:

Set users = new HashSet<>();
         


        
5条回答
  •  温柔的废话
    2021-02-07 03:45

    The default initial capacity is 16, so by passing in 0 you may save a few bytes of memory if you end up not putting anything in the set.

    Other than that there is no real advantage; when you pass 0 the set is created with a capacity of 1 and as soon as you add something it will have to be resized.

提交回复
热议问题