Insert at any position in java.util.List

走远了吗. 提交于 2019-12-05 09:28:37

问题


According to the docs you can insert objects an any position in a List:

The user of this interface has precise control over where in the list each element is inserted.

(source: http://download.oracle.com/javase/6/docs/api/java/util/List.html)

But the following program fails with an IndexOutOfBoundsException:

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> myList = new ArrayList<String>();
        myList.add(0, "derp");
        myList.add(2, "herp");

        for (String s : myList) {
            System.out.println("Le string: " + s);
        }
    }
}

It doesn't help setting initial capacity explicitly, either (which makes some sense since the default value is 10).

Why can't I insert objects at any position as long as its index is lower than the capacity? Is the size always equal to the number of inserted elements?


回答1:


You can insert an object at any valid position. Take a close look at the Javadoc for add(int, E):

Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

In other words, inserting an element always increases the size of the list by 1. You can insert at either end, or in the middle... but you can't insert past the end.

The capacity of an ArrayList is effectively an implementation detail - it controls when the backing array needs to be replaced by a larger one to cope with more elements. The size of a list is the important part here - a list with capacity 100 but size 5 is still only a list of 5 elements, and so inserting at position 67 into such a list would make no sense.




回答2:


List capacity is not the same as its size.

The capacity is a property of array backed lists (such ArrayList or Vector), and it is the allocated size of the backing array (that is, the maximum number of items that you could put before needing to grow the structure).

The size, as you say, is the number of elements present in the list.

Then, why wouldn't you be able to insert an element wherever you want as long as there is space for it? Simple, because the List interface does not specify how the object is backed, and you couldn't do it in something like a LinkedList; so the homogeneous (and correct) behaviour is to throw an exception when that happens.

So you have two options:

  • Initialize the list properly by adding a default values up to your desired size.
  • If null is a sensible default value for you, you can use an array directly.



回答3:


myList.add(2, "herp") should be myList.add(1, "herp")

As increases the size of List is by 1,not 2.




回答4:


ArrayList has two members: capacity and size

capacity is the length of the underlying array, size is the length of the array the ArrayList represents

so you have to add data in the list, so that the ArrayList itself gains the size where you want to insert data




回答5:


The size of the list is Always equal to the number of the inserted elements

Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

javadoc




回答6:


First myList.add(0, "herp") will be inserted then it will check for size. Then, size is 1 but you are inserting at position 2.



来源:https://stackoverflow.com/questions/7847635/insert-at-any-position-in-java-util-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!