java - Java ArrayList 支持稀疏索引吗?

标签 java arraylist hashmap

标题几乎说明了一切。我很难找到这方面的信息,所以我做了一些尝试和错误,我想我会在这里分享我的结果。

<小时/>

由于具有 PHP 背景,我希望 Java 的 ArrayList 类型能够支持稀疏索引。例如,在 PHP 中我可以这样做:

$test = array(
    "Item 1",
    "Item 2",
    "Item 3"
);

unset($test[1]);

echo $test[2];

并拿回“元素 3”。但是,当我在 Java 中尝试类似的操作时:

ArrayList<String> test = new ArrayList<>();

test.add("Item 1");
test.add("Item 2");
test.add("Item 3");

test.remove(1);

System.out.println(test.get(2));

我收到一个IndexOutOfBoundsException。看起来,当您删除元素时,数组会重新索引。也许我错过了一些东西(我对 Java 还很陌生),但在我看来,如果你依赖于知道元素被删除后索引不会改变,你应该使用像 HashMap 这样的东西> 而不是 ArrayList

最佳答案

没有。 Java ArrayList (根据 Javadoc)

this class provides methods to manipulate the size of the array that is used internally to store the list.

按照JLS-10.3. Array Creation

An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable length.

在 Java 中,通常会使用 Map 来实现稀疏Collection。 (如 HashMap 或可能 LinkedHashMap )。

关于java - Java ArrayList 支持稀疏索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32150495/

相关文章:

java - 在 Maven 中我们可以像在 npm 中那样定义脚本吗?

java - 如何合并两个不重复的 ArrayList?

java - 将单词添加到 HashMap,键为单词出现的次数

java - HashMap 新增内容 : how can I sort it?

Java、套接字、BufferedReader 和 StringBuilder

java - 是否可以在 Java 中覆盖泛型类的方法?

Java ArrayList addAll 只添加 1 个元素?

java.util.ConcurrentModificationException 尝试使用迭代器时出错

javascript - 使用不断变化的 HashMap 和 Nodejs 写入 Excel

java - 为什么使用方法局部抽象内部类