Java ArrayList Add (index,element) method inserts an element into an array at the specified locationOriginal October 10, 2013 13:09:37 Tags: java 24540
In the process of developing a project today, you are ready to use ArrayList Add (index,element) to insert elements, naïve thought that this can give list sort
The brief code is as follows:
List List = new ArrayList (50); List.add (0,element); List.add (2,element); List.add (1,element); |
|
Compile run after throw exception, baffled, wait until after looking at the source to find out why, ArrayList Add (index,element) method Source:
|
public void Add (int index, E element) {if (Index > Size | | Index < 0) throw new indexoutofboundsexception ("Index:" +index+ ", Size:" +size); Ensurecapacity (size+1); Increments modcount!! System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index); Elementdata[index] = element; size++; } |
As you can see from the code, this method throws an exception when the number of elements in the array is less than index.
So this method only works if the position you want to insert is less than the number of actual elements in the array.
That is, it is not feasible to have the effect of ordering by inserting elements into a specified position when there is no element in the list.