我想将我的集合初始化为空(不为空),有人可以帮助我吗?这是我的代码
public class Graph {
private Set<Vertex> vertices;
public Graph() {
vertices = {};
}
我知道这是一种错误的方法,但不能做任何其他事情
Set 是一个接口。您需要决定所需的实现,然后使用无参数构造函数进行构造。例如
vertices = new HashSet<Vertex>();
或者
vertices = new TreeSet<Vertext>();
有关vs的更多信息,请参阅此 SO 问题/答案。鉴于这是一个接口,可以存在任意数量的实现(您甚至可以编写自己的实现),但我怀疑您会希望从这两个中的一个开始。TreeSet
HashSet
Set
代替
vertices = {};
和
vertices = new HashSet<Vertex>();
HashSet
这将为您的Set
界面初始化一个空
您需要执行一个构造函数:
public Graph() {
vertices = new HashSet<>();
}
Set
是一个接口定义,因此您需要选择Set
. HashSet
是一个这样的实现,但又TreeSet
是另一个(TreeSet
实际上是 a 的实现SortedSet
)。
public Graph(){
vertices = new HashSet<Vertex>();
}
或者
public Graph(){
vertices = new TreeSet<Vertex>();
}