首页 > 解决方案 > 如何在 Java 中使用数组作为对象属性?

问题描述

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

课程是:

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]+",");
                }
         }

预期的输出是:

1 的邻居是 0,2,0,0,5,

2 的邻居是 1,0,3,4,0,

3 的邻居是 0,2,0,4,0,

4的邻居是0,2,3,0,0,

5 的邻居是 1,0,0,0,0,

当前输出为:

1 的邻居是 1,0,0,0,0,

2 的邻居是 1,0,0,0,0,

3 的邻居是 1,0,0,0,0,

4 的邻居是 1,0,0,0,0,

5 的邻居是 1,0,0,0,0,

标签: javaarraysobjectattributes

解决方案


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

        node(int num, int neigh[])
        {
            this.node_num = num;
            this.neighbors=neigh;
        }   
    public int getNode_num(){
         return node_num;
     }
    public int[] getNeighbors(){
    return neighbors;
    }


}




node nodes[] = new node[n];     

for(i=0;i<nodes.length();i++)
         {

                for(m=0;m<nodes[i].getNeighbors().length();m++)
                {
                    System.out.print(neighbors[m]+",");
                }


         }

推荐阅读