0

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

user2081119
  • 311
  • 3
  • 5
  • 12

4 Answers4

4

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.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

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

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
1
public Graph(){  
  vertices = new HashSet<Vertex>();  
} 

or

public Graph(){  
  vertices = new TreeSet<Vertex>();  
}
Cratylus
  • 52,998
  • 69
  • 209
  • 339
1

Replace

vertices = {};

With

vertices = new HashSet<Vertex>();

This will initialize an empty HashSet for your Set interface

Achrome
  • 7,773
  • 14
  • 36
  • 45