Java arrays change size

前端 未结 7 921
旧巷少年郎
旧巷少年郎 2020-12-10 09:02

I need to change the size of an array, but I cannot simply create another - It needs the same name so I can pass it to a method. Specifically, I need the array to have twice

相关标签:
7条回答
  • 2020-12-10 09:48

    That's not how arrays in Java work:

    int[] anArray;
    anArray = new int[10];
    
    for (int i = 0; i < 10; ++i) {
      // ...
    }
    
    int[] secondArray = anArray;
    
    // Grow "anArray" via secondArray to 20 please:
    secondArray = new int[20]; // No way to alter anArray with this - now two arrays
    

    The closest work around is to make the array the full size when you allocate it, but not use the whole of it until you're ready. I.e. you want to pre-allocate all the space you'll ever need in it.

    int[] anArray;
    anArray = new int[20];
    
    for (int i = 0; i < 10; ++i) { // Still < 10 here
      // ...
    }
    
    int[] secondArray = anArray;
    // no need to change the array, it's already big enough
    

    Either that or use one of the many containers provided.

    0 讨论(0)
  • 2020-12-10 09:50
    int[] a = new int[5];
    // fill a
    int[] b = Arrays.copyOf(a, 10);
    
    0 讨论(0)
  • 2020-12-10 09:57

    Yes, your array variable may reference an array of the same type but different size.

    For changing it internally, an ArrayList might be more easy to use.

    0 讨论(0)
  • 2020-12-10 09:59

    Using ArrayList is better when compared to Array

    0 讨论(0)
  • 2020-12-10 10:01

    I used the Arrays.copyOf method, like this:

        int myArray[] = {1,2,3};
        myArray = Arrays.copyOf(myArray, myArray.length+1);
        //previous line creates a copy of the array and adds one to the size
    
        myArray[3] = 12; // assign the new fourth element the value of 12
        //then loop through the array to output each element
        for(int ctr = 0; ctr<myArray.length; ctr++){
            System.out.println(myArray[ctr]);
        }
    
    0 讨论(0)
  • 2020-12-10 10:07

    You need to create a new array since those are static in size. Then use srcArray = Arrays.copyOf(srcArray, srcArray.length * 2);.

    Alternatively you might want to think about using a list instead of an array. ArrayList is internally backed by an array which will double its size when needed.

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