How do I initialize a set in Java?

It's fine...

public class someClass {
   private Set<Element> pre;

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

      

But it is not...

public class someClass {

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

      

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

+3


source to share


1 answer


In both cases, you are missing initialization Set

, but in the first case it is initialized to null

the default, so the code will compile but throw NullPointerException

when trying to add something to Set

. In the second case, the code will not even compile, since the values ​​of local variables must be assigned before accessing them.

You should fix both examples in

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

      

and



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

      

Of course, the second example Set

is local to someMethod()

, so there is no dot in this code (you are creating a local Set

that you never use).

HashSet

is one implementation Set

you can use. There are others. And if you know in advance the number of individual elements that will be added to Set

, you can specify this number when building Set

. This would improve performance Set

as it would not need to be resized.

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

      

+8


source







All Articles