Different ways to create collections

Discussion in 'Programming' started by Schottky, Mar 28, 2020.

  1. So looking through code of some developers, I see something like this in a lot of cases:
    Code (Java):
    Collection<T> collection = Sets.newHashSet();
    in contrast to something that seems to be more obvious, which is this:
    Code (Java):
    Collection<T> collection = new HashSet<>();
    The first example seems to be somewhat preferred to the latter one.
    From my point of view, I can see no real difference; the method seems to just return a new HashSet. What is the reason people use the first approach, compared to the second one?
    Is it due to the fact that you don't need to provide any type-parameters? But then you don't have to do that in the second example by using the diamond-operator (is this even an operator?)
    Thanks for any answers in advance!
  2. I use the first one most of the times, can't really explain why, it just seems cleaner to me. (Maybe because I don't have to construct the object myself?)
  3. Ye, I tried to do that as well, it indeed seems somewhat cleaner and you can see this kind of behaviour all over mc...
    Still would like to know why (resp. if) this is a better practice
  4. Pretty sure this is because of generic specification in Java 6 - you were obliged to use Collection<String> collection = new HashSet<String>();, and it looks not so good as Collection<String> collection = Sets.newHashSet();. In Java 7 you can use diamond operator, so there's our modern Collection<String> collection = new HashSet<>();.
    • Agree Agree x 1
  5. Choco


    This was the reason these methods existed, yes. You have no reason to be using them at this point in time.
  6. To further reinforce the above comments, here’s what Guava’s docs have to say.
    • Informative Informative x 1