java - 添加数组末尾的对象

标签 java arrays

首先,大家好,阅读此主题。我必须将一个对象添加到数组末尾。例如,在(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/

相关文章:

java - 2个系列之间的区别? (collection1 中的元素,但不在 collection2 中)

Java:在匿名操作处理程序中获取 "this"的正确上下文

c++ - 取消引用一个指向数组类型的结束指针

arrays - Swift:删除文档字段Firestore(云数据库)内字典中的元素

ruby - 分配给数组并替换出现的 nil 值

Java DecimalFormat 舍入错误?

java - J2ME 数据库或数据管理

java - xStream中如何指定接口(interface)的实现?

javascript - 在 Javascript(但不是 Node)中,我如何划分两个 Uint8Arrays?

arrays - 追加到列表/将键添加到 ansible 中的变量