插入java.util.List中的任何位置 [英] Insert at any position in java.util.List

查看:118
本文介绍了插入java.util.List中的任何位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,您可以在List中的任何位置插入对象:

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.

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

但是以下程序因IndexOutOfBoundsException而失败:

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);
        }
    }
}

它没有帮助设置明确的初始容量(这是有道理的,因为默认值是10)。

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?

推荐答案

您可以在任何有效的中插入对象位置。仔细看看Javadoc的 add(int,E)

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


抛出:

IndexOutOfBoundsException - 如果索引超出范围(索引< 0 || index> size())

换句话说,插入元素总是会使列表的大小增加1.您可以在任一端插入,或者在中间...但你不能插入过去结束。

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.

容量 ArrayList 实际上是一个实现细节 - 它控制何时需要用更大的替换替换阵列以应对更多元素。列表的 size 是这里的重要部分 - 容量为100但是大小为5的列表仍然只是5个元素的列表,因此将位置67插入到这样的列表中是没有意义的。

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.

这篇关于插入java.util.List中的任何位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆