Reputation:
I was passing 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've answered A and it is true. But why D is not true? I open the source of ArrayList and find the following chunk of code:
/**
* 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 to any element of an ArrayList using a unique key (index of element). Why does such reasoning is wrong?
Upvotes: 5
Views: 1314
Reputation: 533930
When you use a key/value, you can access the value by looking up the same key no matter how other entries in the Map have changed.
An index is not a key as it can change each time you add or remove an entry. If you keep deleting from the start of a List you can access every element of the list with get(0)
which is clearly not unique to the value.
Upvotes: 1
Reputation: 72884
The elements in the collection are accessed using a unique key.
That would be describing a Map
instead of a List
. I would have asked myself the same question, and indeed the array index can be thought of as a "key". However since such a key would be implicitly unique, the last statement seems more descriptive of a map structure.
Upvotes: 2
Reputation: 3109
unique key
simply means an index
representing element of java.util.ArrayList , there are no 2 different elements have same index
. Right !?
Upvotes: 1
Reputation: 4863
The elements of ArrayList may be accessed by their index into the list, not a key.
You asked why the elements cannot be accessed by a "unique key" ... the answer to that is that the language definition does not allow it. (You may be mistaking the index for a key.)
Elaboration: an index is NOT a key. An index specifies a location within a structure, a key requires one to search a structure for the value of that key. You are getting confused because the indecies are each unique ... but they are not keys
Upvotes: 1
Reputation: 200306
You are indeed right: a list can be accesed using a unique key; the restriction is that you don't 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 wasn't accepted in your exam, it is due to lack of care when writing exam questions. From personal experience I can attest that a lot of care is needed to get an exam right.
Upvotes: 5