【发布时间】:2018-01-17 22:02:46
【问题描述】:
我正在尝试创建一个对象数组。我为 10 个节点分配了一个“node_id”。我还在为类中的其他变量赋值。 'networkInitialization()' 方法中的 for 循环以顺序方式将值分配给 'node_id',但是当我尝试在 main 方法中打印它时,它返回所有 '9'。
import java.util.*;
public class tman {
static int N = 10;
static int k = 5;
static Node nodes[] = new Node[N];
public static void main(String[] args) {
networkInitialization();
for(int i = 0; i<N; i++){
System.out.println(nodes[i].node_id);
}
}
public static void networkInitialization(){
Random random = new Random();
int next;
double theta;
System.out.println("Initializing the network");
for(int i = 0; i<nodes.length; i++){
nodes[i] = new Node();
HashSet<Integer> used = new HashSet<Integer>();
//Nodeid
nodes[i].node_id = i;
// System.out.println(nodes[i].node_id);
//Generating 'k' random neighbors list
for(int j = 0; j<k; j++){
next = random.nextInt(10);
while (used.contains(next)) { //while we have already used the number
next = random.nextInt(N); //generate a new one because it's already used
}
used.add(next);
// System.out.println(next);
nodes[i].neighbors[j] = next;
}
//Calculating XCo and YCo
theta = 3.14/2-(i-1)*3.14/(N-2);
nodes[i].x_co = Math.cos(theta);
nodes[i].y_co = Math.sin(theta);
nodes[i].theta = theta;
// System.out.println(nodes[0].x_co);
}
}
}
class Node{
static int node_id;
static double x_co;
static double y_co;
static double theta;
static int k = 30;
static int neighbors[] = new int[k];
static Map<Integer, int[]> received_list = new HashMap<Integer, int[]>();
int N;
public static int getNodeId(){
return node_id;
}
public static double getXCo(){
return x_co;
}
public static double getYCo(){
return y_co;
}
public static double getTheta(){
return theta;
}
public static int[] getNeighbors(){
return neighbors;
}
public static Map<Integer, int[]> getReceivedList(){
return received_list;
}
public void setNodeId(int node_id){
this.node_id = node_id;
}
public void setXCo(int x_co){
this.x_co = x_co;
}
public void setYCo(int y_co){
this.y_co = y_co;
}
public void setTheta(double theta){
this.theta = theta;
}
public void setNeighbors(int neighbors[]){
this.neighbors = neighbors;
}
}
这是我在 main 方法中得到的输出。
Initializing the network
9
9
9
9
9
9
9
9
9
9
任何人都可以帮助我吗?
更新:
看起来我对static 的理解还不够好。删除 networkInitialization() 方法中的所有静态工作正常。谢谢。
【问题讨论】:
-
我会认真看看你过度使用
static -
当然,我可以删除所有这些。我是初学者。但我的问题是,这个语句 - nodes[i].node_id = i;当我在它之后打印值时正在工作。但是当我在 main 方法中打印它时。我得到了所有 9。
-
是的,它这样做是因为该变量是静态的,即它只有 1 个,每个
nodes[i].node_id指的是同一个。这可能是 What does the 'static' keyword do in a class? 的副本 -
我对@987654334@ 的主题有个人意见,但与大多数事情一样,它是一个双向的门。您需要了解
static实际在做什么,它有什么好处(以及它有什么坏处)以及应该在哪里使用它,因为,是的,它有它的用途,但在你的情况下,你滥用了它而没有完全理解它是如何工作的。您可能想阅读Understanding Class Members
标签: java arrays class object arrayobject