Why can't a Java ArrayList access a unique key?

I passed the Java test and came across the following question (# 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. 

I answered A, and it is true. But why is D not true? I open the ArrayList source and find the following code snippet:

 /** * 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; 

Since we can access any ArrayList element using a unique key (element index). Why is this reasoning wrong?

+5
source share
5 answers

You are really right: the list can be obtained using a unique key; the limitation is that you do not have an arbitrary choice of key.

In fact, maps are also known as โ€œassociative arrays,โ€ emphasizing the equivalence between a List and a Map .

As to why this was not accepted in your exam, this is due to a lack of care when writing exam questions. From personal experience, I can attest that great care is required to get an exam.

+5
source

Elements of the collection are collected using a unique key.

This will describe Map instead of List . I would ask myself the same question, and indeed, the index of the array can be considered as a "key". However, since such a key would be implicitly unique, the last statement seems more descriptive for the map structure.

+2
source

ArrayList elements can be accessed by index in a list, not in a key.

You asked why the elements cannot be accessed with a "unique key" ... the answer to this question is that the definition of the language does not allow this. (You may be mistaken in the pointer for the key.)

Development : an index is NOT a key. The index determines the location within the structure, for the key it is required that it look for the structure for the value of this key. You get confused because indecies are unique ... but they are not keys

+1
source

unique key simply means index representing the java.util.ArrayList element, there are no two different elements having the same index . Right!?

+1
source

When you use a key / value, you can access this value by looking at the same key regardless of how other entries in the Map have changed.

An index is not a key, as it can change every time you add or delete a record. If you keep deleting from the top of the list, you can access each element of the list with get(0) , which is clearly not unique to this value.

+1
source

Source: https://habr.com/ru/post/1201026/


All Articles