Java ArrayList 是否支持稀疏索引? [英] Does Java ArrayList support sparse indicies?

查看:59
本文介绍了Java ArrayList 是否支持稀疏索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Title pretty much says it all. I had a hard time finding information on this, so I did some trial and error, and I thought I would share my results here.

来自 PHP 背景,我希望 Java 的 ArrayList 类型支持稀疏索引.例如,在 PHP 中我可以这样做:

Coming from a PHP background, I expected Java's ArrayList type to support sparse indicies. For example, in PHP I can do:

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

unset($test[1]);

echo $test[2];

并取回Item 3".但是,当我在 Java 中尝试类似的东西时:

And get "Item 3" back. But, when I try something similar in 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.

I get an IndexOutOfBoundsException. It would appear that when you remove the element, the array gets re-indexed. Maybe I'm missing something (I'm pretty new to Java), but it seems to me that if you depend on knowing an index won't change if elements are removed, you should using something like HashMap instead of ArrayList.

推荐答案

没有.Java ArrayList(根据 Javadoc)

No. Java ArrayList (per the Javadoc)

这个类提供了操作内部用于存储列表的数组大小的方法.

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

并且根据 JLS-10.3.数组创建

数组创建表达式指定元素类型、嵌套数组的级别数以及至少一层嵌套的数组长度.数组的长度可用作 final 实例变量 length.

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(例如 HashMapLinkedHashMap).

In Java, one would generally implement a sparse Collection with a Map (like HashMap or possibly LinkedHashMap).

这篇关于Java ArrayList 是否支持稀疏索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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