ZpCikTi
ZpCikTi

Reputation: 115

Add object end of the array

Firstly, Hi everyone that read this topic. I have to add an object to end of array. For instance in (public C(int,int,int) method) I have to extend array "array2" and array2 have two object for (A.B b1 = a1.new B();), have one object for (A.B b2 = a1.new B();).
How can I add object?
Thanks everyone very much. The following code is in test class

<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];
    }}

Upvotes: 0

Views: 158

Answers (2)

duknust
duknust

Reputation: 174

Is easier if you use an ArrayList instead. Arrays have fixed size. The only way is to alocate a new array with greatter size.

Upvotes: 1

npinti
npinti

Reputation: 52185

In Java, arrays have a static size, meaning that once initialized, you cannot change the size.

What you could do, would be to create a new array which will be of size n + m, where n is the current size of the array and m is the amount of items you would like to add. You could then insert the new elements where you would like and use something like System.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length) to move in your previous elements.

That being said, an easier approach would be to use an ArrayList, which provides a means to insert, in a particular location of the array list.

Upvotes: 2

Related Questions