首先,大家好,阅读此主题。我必须将一个对象添加到数组末尾。例如,在(public C(int,int,int)方法)中,我必须扩展数组“array2”> 和 array2 有两个对象 (A.B b1 = a1.new B();),有一个(A.B b2 = a1.new B();) 的对象。
如何添加对象?
非常感谢大家。
以下代码在测试类中
<pre>public class Test{
public static void main(String[] args) {
A a1 = new A();
A.B b1 = a1.new B();
A.B b2 = a1.new B();
A.B.C c1 = b1.new C();
A.B.C c2 = b1.new C ();
A.B.C c3 = b2.new C();}}
//And the other class that following
<pre>public class A{
B [] array1;
class B{
C [] array2;
class C{
private int x;
private int y;
private int z;
//For each creating C object, array "array2" must be extended.
//add new C to end of array,How can I do?
public C(int x, int y, int z){
super();
this.x =x;
this.y=y;
this.z=z;
}
}
//for each creating B object, array "array1" must be extended.
//and add new B to end of array,How can I do that?
public B() {
super();
array2 = new C[0];
}}
public A() {
super();
array1 = new B[0];
}}
最佳答案
在 Java 中,数组具有静态大小,这意味着一旦初始化,就无法更改大小。
您可以做的是创建一个大小为n + m
的新数组,其中n
是< em>当前数组的大小,m
是您要添加的项目数量。然后,您可以在您想要的位置插入新元素并使用类似 System.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length)
的内容。移入之前的元素。
话虽如此,更简单的方法是使用 ArrayList
,它提供了一种方法 insert
,在数组列表的特定位置。
关于java - 添加数组末尾的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30051021/