Add an element to the end of a java array _java array adds an element, how to add an element to a java array

How to add elements to java array

How to add an element to an array, here are three methods:

1. Generally, elements cannot be added to arrays, because their lengths have been set during initialization, and the lengths cannot be changed.

But there is an array whose size can be changed as ArrayList, that is, you can define an ArrayList array, and then use the add(element) method to add elements to it, and add(index,element) to add elements to the specified subscript; the example is as follows :

List list=new ArrayList();

list.add(1);

list.add(2);

list.add(3);

list.add(2,4);

System.out.println(list);

Print result: [1, 2, 4, 3]

2. The idea is to first convert the array into a list, use the add() method of the list to add elements, and then convert the list into an array.

But there will be a trap blind spot. In the process of converting array to list, the asList() method used will return a final, fixed-length ArrayList class, not java.util.ArrayList, so use it directly to add () or remove() is invalid.

List list=new ArrayList();

list=Arrays.asList(sz);

list.add(5);

So what should be done? When defining the list, the array is directly transformed. The code is as follows:

(Note that the Array type here is a wrapper class. If it is a general data type, remember to convert it. For conversion, refer to my other blog posts.)

//Such as List list=new ArrayList();//list=Arrays.asList(str);//This will not work, it must be as follows:

Integer [] sz = {3.2};

List list=new ArrayList(Arrays.asList(sz));//**Convert when defined**

list.add(1,5);

Integer[] nsz=newInteger[list.size()];

list.toArray(nsz);

System.out.println(Arrays.toString(nsz));

结果输出为:[3, 5, 2]

3、第三个方法思路为创建一个新数组,新数组的大小为旧数组大小+1,把旧数组里的元素copy一份进新数组,并把要添加的元素添加进新数组即可。

以上是菜鸟自我总结,如有错误或更好的建议请大佬们指正。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324170227&siteId=291194637