标题几乎说明了一切。我很难找到这方面的信息,所以我做了一些尝试和错误,我想我会在这里分享我的结果。
<小时/>由于具有 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.
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 variablelength
.
在 Java 中,通常会使用 Map
来实现稀疏Collection
。 (如 HashMap
或可能 LinkedHashMap
)。
关于java - Java ArrayList 支持稀疏索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32150495/