为什么不能通过唯一键访问Java ArrayList?

5 java arrays arraylist

我通过了Java测试并遇到了以下问题(№8):

Which statement is true for the class java.util.ArrayList?

    A.  The elements in the collection are ordered.
    B.  The collection is guaranteed to be immutable.
    C.  The elements in the collection are guaranteed to be unique.
    D.  The elements in the collection are accessed using a unique key.
Run Code Online (Sandbox Code Playgroud)

我回答了A,这是真的.但为什么D不是真的?我打开ArrayList的源代码并找到以下代码块:

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
 * DEFAULT_CAPACITY when the first element is added.
 */
private transient Object[] elementData;
Run Code Online (Sandbox Code Playgroud)

因为,我们可以使用唯一键(元素索引)访问ArrayList的任何元素.为什么这样的推理是错误的?

Mar*_*nik 5

你确实是对的:可以使用唯一键来加入列表; 限制是你没有任意选择密钥.

事实上,地图也被称为"关联数组",强调a List和a 之间的等价Map.

至于为什么在你的考试中不接受这个,这是由于在编写考试题目时缺乏关心.根据个人经验,我可以证明需要很多照顾才能使考试正确.

  • 短语"稀疏数组索引3处的元素"对你有意义吗?根据您的定义,它没有意义,因为通常不能实现稀疏数组,使得索引对应于结构内的位置. (2认同)