Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果存在长度为零的数组,我是否应该费心返回空列表?_Java_Collections - Fatal编程技术网

Java 如果存在长度为零的数组,我是否应该费心返回空列表?

Java 如果存在长度为零的数组,我是否应该费心返回空列表?,java,collections,Java,Collections,以该构造函数为例: private final List<ArrayList<Integer>> adjList; public Graph(int vertexCount) { adjList = new ArrayList<ArrayList<Integer>>(vertexCount); for (int i = 0; i < vertexCount; i++) { adjList

以该构造函数为例:

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>());
        }
    }
私有最终列表;
公共图形(int vertexCount){
adjList=新的ArrayList(vertexCount);
对于(int i=0;i
这里有人想要一个顶点列表,他只需提供顶点

   public List<Integer> adj(int vertex) {
        return adjList.get(vertex); 
    }
公共列表调整(int顶点){
返回adjList.get(顶点);
}
现在,如果顶点没有任何节点连接到它,那么返回值将是大小为0的列表。
通过添加显式检查返回Collections.Empty_列表是否有好处,如:如果列表大小为0,则返回Collections.Empty_列表?

无需这样做,您已经实例化了空列表

你能做的就是使用
返回集合.unmodifiableList(adjList.get(v))
,这样
图形的用户就不能修改内部结构了

你应该返回一个,我认为这更能表达你的意图(返回的集合不应该被修改)

也许您可以将该方法的返回值更改为
ImmutableList
,以便客户端可以看到他们甚至不应该尝试更改它。
如果您可以使用。

可以说,这样可以节省一点内存,但需要大量零大小的实例才能发挥作用。
return ImmutableList.copyOf(adjList.get(vertex));