[英]How do I make several objects refer to one common array?
Program creates several Example
objects that each must add their own number into one array.程序创建了几个
Example
对象,每个对象都必须将自己的数字添加到一个数组中。 The problem is that each object refers to its own array, not the common one.问题是每个 object 指的是它自己的数组,而不是公共数组。 How do I make objects refer to one common array?
如何使对象引用一个公共数组?
My code:我的代码:
class Example {
private int[] array = new int[5];
private int number;
public Example(int number) {
this.number = number;
}
public void addInArr(int x) {
for(int i=0; i<array.length; i++) {
if(array[i]==0) {
array[i] = x;
}
break;
}
}
public void showArr() {
for(int i=0; i<array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
for(int i=1; i<6; i++) {
Example obj = new Example(i);
obj.addInArr(i);
obj.showArr();
}
}
}
The code outputs: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0
代码输出:
1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0
The code must output: 1 2 3 4 5
密码必须是 output:
1 2 3 4 5
Perhaps the simplest is to define the array as a static member of the class.也许最简单的方法是将数组定义为 class 的 static 成员。
public class StaticExample {
private static int[] array = new int[5];
...
public int getLength() {
return array.length;
}
}
Your main thread is working in the same array.您的主线程在同一个数组中工作。 Your problem has nothing about multithreading.
您的问题与多线程无关。 Your addInArray() method logic is not correct.
您的 addInArray() 方法逻辑不正确。 You have 5 spots in your array but you always adds the new value at position 0. So the others spots are 0 as the default value for int.
你的数组中有 5 个点,但你总是在 position 0 处添加新值。所以其他点是 0 作为 int 的默认值。
You likely need a new variable to store the current position of your array starting as 0.您可能需要一个新变量来存储从 0 开始的数组的当前 position。
private int position = 0;
public void addInArr(int x) {
array[position] = x;
position++;
}
Attention: If you add more than five numbers it will generate an error because your array has only 5 slots.注意:如果您添加的数字超过五个,则会产生错误,因为您的数组只有 5 个槽。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.