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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With