大统领老婆的妈是白人?# Joke - 肚皮舞运动
g*9
1 楼
写了一个graph的class 但是下面第一种写法是错误的,我不是太明白,是因为
GNode node1 = null;GNode node2 = null吗?这时候node1跟node2并没有allocate
memory,所以就算后面if statement里面的node1 = new GNode(key1) 也只是在if这个
block里面有效的吧,在最后node1.connect(node2)里node1 是不是还是null呢 求指
点。第二个graph class 就可以work的。
public Graph(int[][] adjacencyMatrix) {
nodes = new HashMap();
GNode node1 = null;
GNode node2 = null;
for (int i = 0; i < adjacencyMatrix.length; i++) {
int key1 = i + 1;
if (!nodes.containsKey(key1)){
node1 = new GNode(key1);
nodes.put(key1, node1);
}
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
int key2 = j + 1;
if (!nodes.containsKey(key2){
node2 = new GNode(key2);
nodes.put(key2, node2);
}
if (adjacencyMatrix[i][j] == 1)
node1.connect(node2);
}
}
}
第二种写法 就work的,我只是添加了node1 = nodes.get(key1);跟node2 = nodes.get
(key2);
class Graph {
private HashMap nodes;
public Graph(int[][] adjacencyMatrix) {
nodes = new HashMap();
GNode node1 = null;
GNode node2 = null;
for (int i = 0; i < adjacencyMatrix.length; i++) {
int key1 = i + 1;
node1 = nodes.get(key1);
if (node1 == null){
node1 = new GNode(key1);
nodes.put(key1, node1);
}
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
int key2 = j + 1;
node2 = nodes.get(key2);
if (node2 == null){
node2 = new GNode(key2);
nodes.put(key2, node2);
}
if (adjacencyMatrix[i][j] == 1)
node1.connect(node2);
}
}
}
GNode node1 = null;GNode node2 = null吗?这时候node1跟node2并没有allocate
memory,所以就算后面if statement里面的node1 = new GNode(key1) 也只是在if这个
block里面有效的吧,在最后node1.connect(node2)里node1 是不是还是null呢 求指
点。第二个graph class 就可以work的。
public Graph(int[][] adjacencyMatrix) {
nodes = new HashMap
GNode node1 = null;
GNode node2 = null;
for (int i = 0; i < adjacencyMatrix.length; i++) {
int key1 = i + 1;
if (!nodes.containsKey(key1)){
node1 = new GNode(key1);
nodes.put(key1, node1);
}
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
int key2 = j + 1;
if (!nodes.containsKey(key2){
node2 = new GNode(key2);
nodes.put(key2, node2);
}
if (adjacencyMatrix[i][j] == 1)
node1.connect(node2);
}
}
}
第二种写法 就work的,我只是添加了node1 = nodes.get(key1);跟node2 = nodes.get
(key2);
class Graph {
private HashMap
public Graph(int[][] adjacencyMatrix) {
nodes = new HashMap
GNode node1 = null;
GNode node2 = null;
for (int i = 0; i < adjacencyMatrix.length; i++) {
int key1 = i + 1;
node1 = nodes.get(key1);
if (node1 == null){
node1 = new GNode(key1);
nodes.put(key1, node1);
}
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
int key2 = j + 1;
node2 = nodes.get(key2);
if (node2 == null){
node2 = new GNode(key2);
nodes.put(key2, node2);
}
if (adjacencyMatrix[i][j] == 1)
node1.connect(node2);
}
}
}