I was trying to understand Stream
s in Java8 and intermittently I stumbled upon an interesting thing in the source code of Java8: ArrayList
seems to be implemented twice:
The obvious one: java.util.ArrayList
The non-obvious one: java.util.Arrays.ArrayList
, which is a private class.
One odd difference is that the normal version is way bigger, and implements List<E>
, whereas Arrays.ArrayList
does not do so (directly).
Why is it defined twice? And why with the same name?
The array is a specified-length data structure whereas ArrayList is a variable-length Collection class.
ArrayList internally uses a dynamic array to store its elements. LinkedList uses Doubly Linked List to store its elements. ArrayList is slow as array manipulation is slower. LinkedList is faster being node based as not much bit shifting required.
ArrayList uses an Object class array to store the objects. By default, ArrayList creates an array of size 10. While initializing the Array, we can specify the size of Array. When adding or removing elements, the space in the Array will automatically be adjusted.
ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are non-synchronized classes.
Actually its there ever since Arrays.asList()
introduced. Array's ArrayList is view of the underlying array. If the Array gets changed the ArrayList will get effected and viceversa.
The main benefit, No additional space required because it wont copy the array to a new object (ArrayList), also no additional time to copy the elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With