Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a Set in Java? [duplicate]

This is fine...

public class someClass {
   private Set<Element> pre;

   public void someMethod() {
      pre.add(new Element());
   }
}

But this isn't...

public class someClass {

    public void someMethod() {
       Set<Element> pre;
       pre.add(new Element());
    }
}

What's the correct syntax for the latter case without just turning it into the former?

like image 356
Micromancer Avatar asked Oct 08 '14 05:10

Micromancer


People also ask

Do sets have duplicates Java?

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

How do you clone a set?

Copy Constructor One way of copying a Set is to use the copy constructor of a Set implementation: Set<T> copy = new HashSet<>(original); A copy constructor is a special type of constructor that is used to create a new object by copying an existing object.


1 Answers

In both cases you are missing the initialization of the Set, but in the first case it's initialized to null by default, so the code will compile, but will throw a NullPointerException when you try to add something to the Set. In the second case, the code won't even compile, since local variables must be assigned a value before being accessed.

You should fix both examples to

private Set<Element> pre = new HashSet<Element>();

and

Set<Element> pre = new HashSet<Element>();

Of course, in the second example, the Set is local to someMethod(), so there's no point in this code (you are creating a local Set which you are never using).

HashSet is one implementation of Set you can use. There are others. And if your know in advance the number of distinct elements that would be added to the Set, you can specify that number when constructing the Set. It would improve the Set's performance, since it wouldn't need to be re-sized.

private Set<Element> pre = new HashSet<Element>(someInitialSize);
like image 86
Eran Avatar answered Oct 16 '22 05:10

Eran