How to increase the size of an array in Java?

前端 未结 10 634
粉色の甜心
粉色の甜心 2021-01-04 04:00

I want to store as many elements as desired by the user in an array. But how do I do it.

If I were to create an array, I must do so with a fixed size. Every time a

10条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 04:32

    public class IncreaseArraySize {
     public static void main(String[] args) {
        int arr[] = new int[5];
          for (int i = 0; i < arr.length; i++) {
                arr[i] = 5;
          }
          for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
          }
           System.out.println(" ");
           System.out.println("Before increasing Size of an array :" + arr.length);
    
    
            int arr2[] = new int[10];
    
            arr = arr2;
            arr2 = null;
            for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println("");
        System.out.println("After increasing Size of an array : " + arr.length);
    }
    }
    

提交回复
热议问题