The Java ArrayList Add (index,element) method inserts an element into the array at the specified position __java

Source: Internet
Author: User
Tags throw exception
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.