首先,大家好,阅读此主题。我必须在数组末尾添加一个对象。例如,在(公共C(int,int,int)方法)中,我必须扩展数组“ array2”,并且array2对于(AB b1 = a1.new B();)具有两个对象,对于(AB 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中,数组具有静态大小,这意味着一旦初始化,就无法更改大小。
您可以做的是创建一个新数组,其大小为size n + m
,其中为该数组n
的当前大小,为m
要添加的项数。然后,您可以在所需的位置插入新元素,并使用类似的方法System.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length)
来移动先前的元素。
话虽这么说,一种更简单的方法是使用,在数组列表的特定位置ArrayList
提供的手段insert
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句