I am trying to create an array of objects. There are 10 nodes for which I am assigning a 'node_id'. I am also assigning values to other variables in the class. The for loop in 'networkInitialization()' method assigns values to 'node_id' in a sequential manner, but when I try to print it in main method it returns all '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;
}
}
This is the output I am getting in main method.
Initializing the network
9
9
9
9
9
9
9
9
9
9
Anyone can help me on this ?
UPDATE :
Looks like I have not understood static
well enough. Removing all the static in the networkInitialization()
method worked correctly. Thank you.