问题嵌套在代码中。我有2个代码选项。每个都列出了利弊。想知道一种首选方法。
OPTION1:
public class Graph {
private final List<ArrayList<Integer>> adjList;
/**
* DISADVANTAGE:
* 1. Slow to create an object.
* 2. Memory allocated prematurely, lazy initialization could be used to speed up object creation.
*/
public Graph(int vertexCount) {
adjList = new ArrayList<ArrayList<Integer>>(vertexCount);
for (int i = 0; i < vertexCount; i++) {
adjList.add(new ArrayList<Integer>());
}
this.vertexCount = vertexCount;
}
/**
* ADVANTAGE:
* 1. No synchronization issues, reducing complexity and overhead of sync.
* 2. No need to null check, since constructor has taken care of lot .
*/
public void addEdge(int vertexFrom, int vertexTo) {
adjList.get(vertexFrom).add(vertexTo);
adjList.get(vertexTo).add(vertexFrom);
}
/**
* DISADVANTAGE:
*
* Inspite of knowing that none of the List<Integers> are null, an extra check for size == 0, needed to return Collections.EMPTY_LIST
* Eg:
* if (adjList.get(vertex).size == 0) { return Collections.EMPTY_LIST; }
* return adjList.get(vertex).size
*/
public List<Integer> adj(int vertex) {
return adjList.get(vertex);
}
}
选项2
public class Graph {
private final List<ArrayList<Integer>> adjList;
private final int vertexCount;
private int edgeCount;
/**
* ADVANTAGE: quick construction
*
*/
public Graph(int vertexCount) {
adjList = new ArrayList<ArrayList<Integer>>(vertexCount);
this.vertexCount = vertexCount;
}
/**
* DISADVANTAGE:
* 1. Effort spent on null checks.
*
* 2. Thread safety complications.
*/
public void addEdge(int vertexFrom, int vertexTo) {
if ( adjList.get(vertexFrom) == null ) {
adjList.add(vertexFrom, new ArrayList<Integer>())
}
if ( adjList.get(vertexTo) == null ) {
adjList.add(vertexTo, new ArrayList<Integer>())
}
adjList.get(vertexFrom).add(vertexTo);
adjList.get(vertexTo).add(vertexFrom);
edgeCount++;
}
public List<Integer> adj(int vertex) {
if (adjList.get(vertex) == 0) return Collections.EMPTY_LIST;
return adjList.get(vertex);
}
public List<ArrayList<Integer>> getGraph() {
return adjList;
}
}