Java 将新对象添加到具有硬编码长度的对象数组中,而不使用arraylist
只是想知道如何将另一个对象添加到固定对象数组中。您会更改数组的长度吗 对象长度为43Java 将新对象添加到具有硬编码长度的对象数组中,而不使用arraylist,java,arrays,Java,Arrays,只是想知道如何将另一个对象添加到固定对象数组中。您会更改数组的长度吗 对象长度为43 for(int i=0;i<count;i++){ object[count] =new Movie(movieID,movieTitle,Director,Writer,Duration,Genre,Classification,releaseDate,Rating); } 用于(int i=0;i您可以简单地将数组的引用发送到一个方法,然后创建一个大小为+1的新数组,填充数组并返回它,尽管这是一种
for(int i=0;i<count;i++){
object[count] =new Movie(movieID,movieTitle,Director,Writer,Duration,Genre,Classification,releaseDate,Rating);
}
用于(int i=0;i您可以简单地将数组的引用发送到一个方法,然后创建一个大小为+1的新数组,填充数组并返回它,尽管这是一种不好的做法,如果您需要动态大小,只需使用arraylist,您肯定需要重新分配原始数组,因为数组的大小是固定的。这个小示例说明了这是可以做到的
public class A {
private int i;
public A(int i) {
this.i = i;
}
public static void main(String[] args) {
// Original array with the size 1;
A[] arr = new A[1];
// One default item
arr[0] = new A(0);
// Reassign array here, use a method returning a new instance of A[]
arr = add(arr, new A(1));
// just for printing.
for(A a : arr) {
System.out.println(a.i);
}
}
public static A[] add(A[] inputArr, A newItem) {
// The array will have another item, so original size + 1
A[] buffer = new A[inputArr.length+1];
// Copy the original array into the new array.
System.arraycopy(inputArr, 0, buffer, 0, inputArr.length);
// Add the new item at the end
buffer[buffer.length-1] = newItem;
// Return the "increased" array
return buffer;
}
}
现在,输出显示数组中有两个项
O/p:
总而言之,在这里使用列表会更好,但由于您不想要它,我希望这个示例可以指导您使用数组。数组有固定大小。您不能更改,除非您还剩下一些可用索引,否则无法添加。对于可变数量的条目,您最好使用List
而不是数组
使用ArrayList有什么问题?
0
1