Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between multiple implementations of ArrayList in the (Java8) source code [duplicate]

I was trying to understand Streams 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?

like image 682
skiwi Avatar asked Feb 26 '14 18:02

skiwi


People also ask

What is the difference between array and ArrayList in Java?

The array is a specified-length data structure whereas ArrayList is a variable-length Collection class.

What is difference between LinkedList and ArrayList?

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.

How are Arraylists implemented in Java?

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.

Which of the following interface is implemented in ArrayList and LinkedList?

ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are non-synchronized classes.


1 Answers

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.

like image 179
RP- Avatar answered Sep 28 '22 06:09

RP-