Java:为什么我的对象数组会覆盖循环中以前的所有数据?
我尝试创建一个节点数组,其中一个节点位于数组中的特定位置 例如:Java:为什么我的对象数组会覆盖循环中以前的所有数据?,java,arrays,loops,overwrite,Java,Arrays,Loops,Overwrite,我尝试创建一个节点数组,其中一个节点位于数组中的特定位置 例如: 我在数组中添加一个节点,并将其编号设置为1。 我在数组中的下一个位置添加另一个节点,并将其编号设置为2。 两个节点现在都得到了数字2 代码示例: public static String run(InputStream in) { Scanner sc = new Scanner(in); //indicating values sc.nextInt(); /* int vertices = */
我在数组中添加一个节点,并将其编号设置为1。
我在数组中的下一个位置添加另一个节点,并将其编号设置为2。
两个节点现在都得到了数字2 代码示例:
public static String run(InputStream in) {
Scanner sc = new Scanner(in);
//indicating values
sc.nextInt(); /* int vertices = */
int edge = sc.nextInt();
int start = sc.nextInt();
int end = sc.nextInt();
if (start == end) {
sc.close();
Path = "yes";
} else {
nodes = new Node[edge + 1];
for (int i = 1; i < edge; i++) {
//Node values
int number = sc.nextInt();
int next = sc.nextInt();
sc.nextInt(); /* int distance = */
Node node = new Node(number, next);
if (nodes[number] == null) {
nodes[number] = (node);
} else {
nodes[number].addChild(next);
}
}
hasPath(nodes[start], end);
}
sc.close();
return Path;
}
公共静态字符串运行(InputStream-in){
扫描仪sc=新扫描仪(英寸);
//指示值
sc.nextInt();/*int顶点=*/
int edge=sc.nextInt();
int start=sc.nextInt();
int end=sc.nextInt();
如果(开始==结束){
sc.close();
Path=“是”;
}否则{
节点=新节点[边+1];
对于(int i=1;i
节点代码示例:
import java.util.ArrayList;
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private static int number;
public Node(int n, int next){
number = n;
childs.add(next);
}
public int getNumber(){
return number;
}
public void addChild(int child){
childs.add(child);
}
import java.util.ArrayList;
公共类节点{
private ArrayList childs=new ArrayList();
私有静态整数;
公共节点(int n,int next){
数字=n;
添加(下一步);
}
public int getNumber(){
返回号码;
}
公共void addChild(int child){
添加(child);
}
有人能帮我吗?问题在于声明
编号成员静态。这意味着节点类只有一个这样的成员,而不是每个实例都有自己的成员。只需将其定义为实例变量,您应该是fine:
public class Node {
private ArrayList<Integer> childs = new ArrayList<Integer>();
private int number; // Note the static was removed
// rest of the class
公共类节点{
private ArrayList childs=new ArrayList();
private int number;//注意,已删除静态
//班上其他同学
成功了,thnx!@EmielRietdijk:如果这解决了您的问题,您应该将其标记为“已接受”!