如何访问Java中用作对象属性的数组?

时间:2018-08-06 16:30:18

标签: java arrays object attributes

我创建了一个带有数组属性的类。我还创建了一个对象数组。我想知道如何调用特定对象的数组元素?

课程是:

public class node
{
    public int node_num;
    public int total_weight;
    public int[] neighbors;

     node(int num, int weight,int neigh[])
    {
        this.node_num = num;     //node number      
        this.total_weight = weight;   //row total
        this.neighbors=neigh;     //adjacent nodes
    }       
}

我的主要功能是:

public static void main(String[] args) 
{
    int n=5;
    int temp1,temp2;
        int adj_mat[][]= {{0,4,0,0,10},{4,0,6,2,0},{0,6,0,4,0},{0,2,4,0,0},{10,0,0,0,0}};     //populating the weighted adjacency matrix


        int i=0, j=0;
        int n1[]=new int[n];

        cluster cluster1=new cluster();

        node nodes[] = new node[n];

        for (i = 0; i < n; i++)
            {
             int sum=0,k=0;

                for (j = 0; j < n; j++)
                {                   
                    if(adj_mat[i][j]!=0)
                    {
                        sum= sum+adj_mat[i][j];  
                        n1[k]=j+1;
                        k=k+1;
                    }
                    else
                    {
                        n1[k]=0;
                        k=k+1;
                    }
                }
                        nodes[i]=cluster1.new node(i+1,sum,n1);
            }
        int m;
         for(i=0;i<n;i++)
         {   
             System.out.print("\nNeighbor of "+nodes[i].node_num +" is ");
                for(m=0;m<5;m++)
                {
                    System.out.print(nodes[i].neighbors[m]+",");
                }
         }

预期输出为:

Neighbor of 1 is 0,2,0,0,5,
Neighbor of 2 is 1,0,3,4,0,
Neighbor of 3 is 0,2,0,4,0,
Neighbor of 4 is 0,2,3,0,0,
Neighbor of 5 is 1,0,0,0,0,

当前输出为:

Neighbor of 1 is 1,0,0,0,0,
Neighbor of 2 is 1,0,0,0,0,
Neighbor of 3 is 1,0,0,0,0,
Neighbor of 4 is 1,0,0,0,0,
Neighbor of 5 is 1,0,0,0,0,

1 个答案:

答案 0 :(得分:0)

看看您的预期输出:最后一个元素是Process

然后看看创建数组的位置:它在循环之外。

因此,在循环中调用Operation Neighbor of 5 is 1,0,0,0,0,指的是所有节点的相同数组,即,您覆盖{ {1}}在所有迭代中,最后的值是最后一个节点的值。

要解决此问题,请在创建节点的循环中将new node(i+1,sum,n1)行移动到循环中:

n1