How can we dynamically allocate and grow an array

前端 未结 8 1811
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 16:01

I am working on a project, but I cannot use any existing java data structures (ie, ArraysList, trees, etc)

I can only use arrays. Therefore, I need to dynamically up

8条回答
  •  天命终不由人
    2020-12-05 17:01

    public class Arr {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int a[] = {1,2,3};
            //let a[] is your original array
            System.out.println(a[0] + " " + a[1] + " " + a[2]);
            int b[];
            //let b[] is your temporary array with size greater than a[]
            //I have took 5
            b = new int[5];
            //now assign all a[] values to b[]
            for(int i = 0 ; i < a.length ; i ++)
                b[i] = a[i];
            //add next index values to b
            b[3] = 4;
            b[4] = 5;
            //now assign b[] to a[]
            a = b;
            //now you can heck that size of an original array increased
            System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " 
        + a[4]);
        }
    
    }
    

    Output for the above code is:

    1 2 3

    1 2 3 4 5

提交回复
热议问题