How to increase the size of an array in Java?

前端 未结 10 633
粉色の甜心
粉色の甜心 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:30

    By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.

    package com.google.service;
    
    import java.util.Arrays;
    
    public class StringArrayAutoIncrement {
        public static void main(String[] args) {
            String[] data = new String[] { "a", "b", "c", "d", "e" };
            String[] array = new String[0];// array initialize with zero
            int incrementLength = 1;
            for (int i = 0; i < data.length; i++) {
                array = Arrays.copyOf(data, i + incrementLength);// increment by +1
            }
            /**
             * values of array after increment
             */
            for (String value : array) {
                System.out.println(value);
            }
        }
    }
    

    Output:

    a
    b
    c
    d
    e
    

提交回复
热议问题