以这个构造函数为例:
private final List<ArrayList<Integer>> adjList;
public Graph(int vertexCount) {
adjList = new ArrayList<ArrayList<Integer>>(vertexCount);
for (int i = 0; i < vertexCount; i++) {
adjList.add(new ArrayList<Integer>());
}
}
这里有人想要一个顶点列表,他只需提供顶点即可。
public List<Integer> adj(int vertex) {
return adjList.get(vertex);
}
现在如果顶点没有任何节点连接到它,那么返回值将是大小为 0 的列表。 通过添加显式检查来返回 Collections.Empty_List 是否有优势:如果列表大小为 0,则返回 Collections.Empty_List ?
最佳答案
无需这样做,您已经实例化了空列表。
你可以做的是使用return Collections.unmodifyingList(adjList.get(v))
,这样你的Graph
的用户就无法修改内部结构
关于java - 如果存在零长度数组,我是否应该返回空列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18240004/