Two ways to add elements to a java array

The length of the array is fixed before use, so the original length of the array cannot be changed. Based on this, the following two methods are provided to add element data

1 Create a new array whose length is the original array plus 1, then add the original array data to the new array, and finally add the required new data

        String[] s1 = {"a","b","c"};
        String[] s2 = new String[s1.length+1];
        for (int i = 0; i < s1.length; i++) {
            s2[i] = s1[i];
        }
        s2[s1.length] = "d";

2 First convert the array into a list, add the list to a new ArrayList, then use the add() method of the new ArrayList to add elements, and finally convert the new ArrayList into an array

        String[] s1 = {"a","b","c"};
        List<String> list = new ArrayList<>(Arrays.asList(s1));
        list.add(1,"d");
        String[] s2 = new String[list.size()];
        list.toArray(s2);

Guess you like

Origin blog.csdn.net/xiansibao/article/details/131203518