为什么我的Object数组的值在Java中仍然相同
我不明白为什么我的对象数组仍然保持不变。我试图从数组中计算索引。如何计算索引为什么我的Object数组的值在Java中仍然相同,java,arrays,sorting,Java,Arrays,Sorting,我不明白为什么我的对象数组仍然保持不变。我试图从数组中计算索引。如何计算索引 public class TryArray { Students[] arr; public void add(Students std) { for (int i = 0; i < arr.length ; i++) { arr[i] = std; System.out.println(std); //it willbe more t
public class TryArray {
Students[] arr;
public void add(Students std) {
for (int i = 0; i < arr.length ; i++) {
arr[i] = std;
System.out.println(std); //it willbe more than one time displayed
break;
}
}
public TryArray(int lengthOfArray) { //Constructor for the length Array
arr = new Students[lengthOfArray];
}
}
预期产出:
我错过什么了吗 您当前的代码中有很多错误的概念。首先,使用要添加的元素设置数组的所有元素。其次,在add方法中,打印变量乘以数组的长度,而不考虑正确的结果 您的TryArray类的代码可以这样重写:
public class TryArray {
//array to store the students (elements)
private Students[] arr;
//counter of how many students are stored by this instance
private int size;
public void add(Students std) {
/*
the code here makes no sense, see explanation above
for (int i = 0; i < arr.length ; i++) {
arr[i] = std;
System.out.println(std); //it willbe more than one time displayed
break;
}
*/
if (size < arr.length) {
arr[size++] = std;
//this is for testing purposes only, in real life code
//you shall avoid code like this here
System.out.println(std);
}
}
public TryArray(int lengthOfArray) { //Constructor for the length Array
arr = new Students[lengthOfArray];
}
}
让我们看两件事:1学生课堂上的字段不能是静态的。2我们需要查看TryArrayadd的代码。我不确定索引的确切含义是什么,但在for循环中,您有一个中断;打印add中的第一个元素之后。因此,您只能看到[0]元素。在Students类中,它只是构造函数,其他什么都没有。这就是TryArrayadd@LuiggiMendozabut的代码,如果我不写break;我想显示我的数组**的对象,它将显示两次。我想显示**一次@KevinOIf,我把循环放在里面,如下所示:arr[I]=std,不间断;并使用System.out.println显示,它将被多次显示
1, Bob, Julius
2, Joe, Chris
3, Christian, Henderson
public class TryArray {
//array to store the students (elements)
private Students[] arr;
//counter of how many students are stored by this instance
private int size;
public void add(Students std) {
/*
the code here makes no sense, see explanation above
for (int i = 0; i < arr.length ; i++) {
arr[i] = std;
System.out.println(std); //it willbe more than one time displayed
break;
}
*/
if (size < arr.length) {
arr[size++] = std;
//this is for testing purposes only, in real life code
//you shall avoid code like this here
System.out.println(std);
}
}
public TryArray(int lengthOfArray) { //Constructor for the length Array
arr = new Students[lengthOfArray];
}
}