0

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];
    }}
1
  • 4
    You can't. Arrays have a fixed size. You'll need to either create a new Array size is currentSize + 1, and copy your data, or use a List. Commented May 5, 2015 at 10:55

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.