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);