java - 如何在 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,
解决方案
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]+",");
}
}
推荐阅读
- http - 为什么当我在 ip 而不是主机名上卷曲时需要额外的 `-k` 标志?
- python - pd.get_dummies() 带分隔符和计数
- postgresql - 违反外键约束
- python - 有没有办法自定义 PyInputPlus 显示的错误消息?
- css - 如何知道浏览器窗口大小?
- google-glass - 如何在 Google Glass Enterprise Edition 2 上启用调试模式?
- bash - 删除每一行的反斜杠
- git - 如何在不使用 gerrit ui 的情况下添加补丁集描述
- android - Flutter 从另一个文件调用表单保存功能
- sql - Oracle SQL - 根据签入和签出记录获取日期之间的差异