插入到java.util.List中的任意位置

发布于 2024-12-11 07:42:40 字数 746 浏览 0 评论 0原文

根据文档,您可以将对象插入列表中的任何位置:

此界面的用户可以精确控制每个元素在列表中的插入位置。

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

但是以下程序失败并出现 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)。

为什么只要索引低于容量就不能在任何位置插入对象?大小总是等于插入元素的数量吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

梦里的微风 2024-12-18 07:42:40

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

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

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

ArrayList容量实际上是一种实现细节 - 它控制何时需要用更大的数组替换后备数组以处理更多元素。列表的大小是这里的重要部分 - 容量为 100 但大小为 5 的列表仍然只有 5 个元素的列表,因此在位置 67 处插入这样的列表是没有意义的。

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.

绝情姑娘 2024-12-18 07:42:40

列表容量与其大小不同。

容量是数组支持列表(例如ArrayListVector)的一个属性,它是支持数组的分配大小(即,可容纳的最大项目数)。您可以在需要增长结构之前放置)。

正如您所说,大小是列表中存在的元素数量。

那么,为什么只要有空间就不能在任何地方插入元素呢?很简单,因为 List 接口没有指定如何支持对象,并且您无法在 LinkedList 之类的东西中做到这一点;因此,同质(且正确)的行为是在发生这种情况时抛出异常。

因此,您有两个选择:

  • 通过添加默认值到您想要的大小来正确初始化列表。
  • 如果 null 对您来说是一个合理的默认值,您可以直接使用数组。

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.
守望孤独 2024-12-18 07:42:40

myList.add(2, "herp") 应该是 myList.add(1, "herp")

因为 List 的大小增加了 1,而不是 2。

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

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

凤舞天涯 2024-12-18 07:42:40

ArrayList 有两个成员:capacity 和 size

容量是底层数组的长度,size 是 ArrayList 表示的数组的长度

,因此您必须在列表中添加数据,以便 ArrayList 本身获得您想要插入的大小数据

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

终难遇 2024-12-18 07:42:40

列表的大小始终等于插入元素的数量

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

javadoc

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

掐死时间 2024-12-18 07:42:40

首先将插入 myList.add(0, "herp") 然后检查大小。然后,大小为 1,但您要在位置 2 插入。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文