How can we dynamically allocate and grow an array

前端 未结 8 1776
伪装坚强ぢ
伪装坚强ぢ 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

    Visual Basic has a nice function : ReDim Preserve.

    Someone has kindly written an equivalent function - you can find it here. I think it does exactly what you are asking for (and you're not re-inventing the wheel - you're copying someone else's)...

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题