6

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?

Eran
  • 387,369
  • 54
  • 702
  • 768
Micromancer
  • 81
  • 1
  • 1
  • 4

1 Answers1

12

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);
Eran
  • 387,369
  • 54
  • 702
  • 768