I have been trying to compare definition of list and its implementation in Java as I feel there is a mismatch.
Definition Of List DataStructure: a list or sequence is an abstract data type that implements an ordered collection of values, where the same value may occur more than once. [Taken from : http://en.wikipedia.org/wiki/List_(abstract_data_type) ]
Now an ordered collection maintains the order of insertion of elements.
Java Implementation of List -> ArrayList : As per this implementation, I have following points:
- If I initialize an
ArrayListof say size 5, then I cannot directly insert element at 5th position without inserting elements at position 1,2,3,4 because it will go against ordering principle. So Java gives exception here which I completely agree with. ArrayListprovides methods like "set(int index, E element)" and "add(int index, E element)" using which we can replace elements in middle of list and can also insert new elements in middle of list. I do not understand this. It is going against principle of ordering as insertion order is not maintained.
I feel 1st and 2nd point are in conflict with each other and 2nd point is against principle of ordering or may be I am missing something.
Can somebody please explain where I am going wrong in my understanding of List here?
Abstract Definition