Reputation: 321
I want to initialize my set to be empty (not null), can anyone help me? Here is my code
public class Graph {
private Set<Vertex> vertices;
public Graph() {
vertices = {};
}
I know that this is a wrong way to do that, but couldn't do anything else
Upvotes: 0
Views: 612
Reputation: 7821
Replace
vertices = {};
With
vertices = new HashSet<Vertex>();
This will initialize an empty HashSet
for your Set
interface
Upvotes: 1
Reputation: 272357
Set is an interface. You need to decide on the implementation required, and then construct using a no-args constructor. e.g.
vertices = new HashSet<Vertex>();
or
vertices = new TreeSet<Vertext>();
See this SO question/answer for more info on TreeSet
vs HashSet
. Given that Set
is an interface, any number of implementations could exist (you could even write your own) but I suspect you'll want one of these two to begin with.
Upvotes: 4
Reputation: 54094
public Graph(){
vertices = new HashSet<Vertex>();
}
or
public Graph(){
vertices = new TreeSet<Vertex>();
}
Upvotes: 1
Reputation: 16605
You need to execute a constructor:
public Graph() {
vertices = new HashSet<>();
}
Set
is an interface definition, so you will need to pick a concrete implementation of Set
. HashSet
is one such implementation, but TreeSet
is another (TreeSet
is actually an implementation of a SortedSet
).
Upvotes: 1