Are lists the same as arrays in Java?

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed.

We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java. Since Java 5, primitives are automatically converted in objects which is known as auto-boxing.

import java.util.*; public class ListExample { public static void main[String[] args] { List list=new ArrayList[]; list.add[Integer.valueOf[10]];//storing Integer object list.add[20];//Now compiler converts it into Integer.valueOf[20] which is object list.add[30]; System.out.println["Traversing List..."]; for[Integer i:list]{ System.out.println[i]; } } }

Output:

Traversing List... 10 20 30

Next TopicJava Collections Interview Questions

For Videos Join Our Youtube Channel: Join Now

  • Send your Feedback to [email protected]

An array [something like int[]] is a built in type while ArrayList is a regular class part of the Java standard library.

When to use which?

Sometimes you must use an array. For example:

  • An API method takes an array as argument or returns an array
  • You need to work with primitives for performance reasons

Unless you have a specific reason to use an array [such as those mentioned above], use a List, such as an ArrayList.

Resizing

Once you've created an array, it can't be resized. You can for instance not append an element to the end of an array, or remove an element.

Most list types [including ArrayList] provide List.add and List.remove which allows it to grow and shrink.

Insertion

Both arrays and lists allow you to update the content at a specific index.

arr

[

5

] =

17

;

list

.

set

[

5

,

17

];

Lists however, also allows you to insert an element in the middle, shifting all subsequent elements from index i to i + 1.

list

.

add

[

5

,

17

];

Primitives

An arrray can store primitive values. Lists can not. You can have a List of integers, but you'll have to use List. List doesn't work. [Support for this is under way and might be available in something like Java 13. See JEP 218: Generics over Primitive Types.]

Autoboxing: Luckily there's something called autoboxing which silently transforms an int to an Integer behind the scenes. So despite the fact that a List can only hold Integer values, we can still use list.add[5], i.e. we don't have to write list.add[new Integer[5]].

Generic elements

You can't create an array of generic elements. This won't compile:

Set

[]

sets

=

new

Set

[

3

];

This however works fine:

List

sets

=

new

ArrayList

[];

There is however a simple workaround for the array case. See Java: Generic array creation.

Immutability

There's no way to make the elements of an array "final". If you write for instance

final

int

[]

arr

= {

1

,

2

,

3

};

Something like arr[1] = 77 is still allowed.

Element immutability can be achieved for lists by doing:

List

list

=

Collections

.

unmodifiableList

[

Arrays

.

asList

[

1

,

2

,

3

]];

Covariance

A String[] is a subtype of Object[]. This allows us to write:

String

[]

strings

=

new

String

[

1

];

Object

[]

objects

=

strings

;

objects

[

0

] =

new

Object

[];

Although it throws an exception when executed!

A List is however not a subtype of a List. This for example does not compile:

List

strings

=

new

ArrayList

[];

List

objects

=

strings

;

objects

.

add

[

new

Object

[]];

Put in fancy computer science terms: Arrays are covariant, while lists are not.

List methods

You can't use List methods on arrays… WRONG. There's in fact a bridge from the array world over to the List world. The bridge is called Arrays.asList. This method returns a List implementation backed by the provided array, which means that modifications to the list affect the original array.

Here's an example using List.replaceAll on an array:

String

[]

strs

= {

"a"

,

"b"

,

"c"

,

"d"

};

Arrays

.

asList

[

strs

].

replaceAll

[

s

->

s

+

s

];

Note however, that since the backing array can't shrink or grow, operations such as List.add will throw UnsupportedOperationException.

Although the answers proposing to use ArrayList do make sense in most scenario, the actual question of relative performance has not really been answered.

There are a few things you can do with an array:

  • create it
  • set an item
  • get an item
  • clone/copy it

General conclusion

Although get and set operations are somewhat slower on an ArrayList [resp. 1 and 3 nanosecond per call on my machine], there is very little overhead of using an ArrayList vs. an array for any non-intensive use. There are however a few things to keep in mind:

  • resizing operations on a list [when calling list.add[...]] are costly and one should try to set the initial capacity at an adequate level when possible [note that the same issue arises when using an array]
  • when dealing with primitives, arrays can be significantly faster as they will allow one to avoid many boxing/unboxing conversions
  • an application that only gets/sets values in an ArrayList [not very common!] could see a performance gain of more than 25% by switching to an array

Detailed results

Here are the results I measured for those three operations using the jmh benchmarking library [times in nanoseconds] with JDK 7 on a standard x86 desktop machine. Note that ArrayList are never resized in the tests to make sure results are comparable. Benchmark code available here.

Array/ArrayList Creation

I ran 4 tests, executing the following statements:

  • createArray1: Integer[] array = new Integer[1];
  • createList1: List list = new ArrayList [1];
  • createArray10000: Integer[] array = new Integer[10000];
  • createList10000: List list = new ArrayList [10000];

Results [in nanoseconds per call, 95% confidence]:

a.p.g.a.ArrayVsList.CreateArray1 [10.933, 11.097] a.p.g.a.ArrayVsList.CreateList1 [10.799, 11.046] a.p.g.a.ArrayVsList.CreateArray10000 [394.899, 404.034] a.p.g.a.ArrayVsList.CreateList10000 [396.706, 401.266]

Conclusion: no noticeable difference.

get operations

I ran 2 tests, executing the following statements:

  • getList: return list.get[0];
  • getArray: return array[0];

Results [in nanoseconds per call, 95% confidence]:

a.p.g.a.ArrayVsList.getArray [2.958, 2.984] a.p.g.a.ArrayVsList.getList [3.841, 3.874]

Conclusion: getting from an array is about 25% faster than getting from an ArrayList, although the difference is only on the order of one nanosecond.

set operations

I ran 2 tests, executing the following statements:

  • setList: list.set[0, value];
  • setArray: array[0] = value;

Results [in nanoseconds per call]:

a.p.g.a.ArrayVsList.setArray [4.201, 4.236] a.p.g.a.ArrayVsList.setList [6.783, 6.877]

Conclusion: set operations on arrays are about 40% faster than on lists, but, as for get, each set operation takes a few nanoseconds - so for the difference to reach 1 second, one would need to set items in the list/array hundreds of millions of times!

ArrayList's copy constructor delegates to Arrays.copyOf so performance is identical to array copy [copying an array via clone, Arrays.copyOf or System.arrayCopy makes no material difference performance-wise].

Page 2

ArrayList internally uses array object to add[or store] the elements. In other words, ArrayList is backed by Array data -structure.The array of ArrayList is resizable [or dynamic].

Array is faster than ArrayList because ArrayList internally uses an array. if we can directly add elements in Array and indirectly add an element in Array through ArrayList always directly mechanism is faster than an indirect mechanism.

There is two overloaded add[] methods in ArrayList class:

  1. add[Object]: adds an object to the end of the list.
  2. add[int index, Object ]: inserts the specified object at the specified position in the list.

How the size of ArrayList grows dynamically?

public boolean add[E e] { ensureCapacity[size+1]; elementData[size++] = e; return true; }

An important point to note from the above code is that we are checking the capacity of the ArrayList, before adding the element. ensureCapacity[] determines what is the current size of occupied elements and what is the maximum size of the array. If the size of the filled elements [including the new element to be added to the ArrayList class] is greater than the maximum size of the array then increase the size of the array. But the size of the array can not be increased dynamically. So what happens internally is new Array is created with the capacity

Till Java 6

int newCapacity = [oldCapacity * 3]/2 + 1;

[Update] From Java 7

int newCapacity = oldCapacity + [oldCapacity >> 1];

also, data from the old array is copied into the new array.

Having overhead methods in ArrayList that's why Array is faster than ArrayList.

Video liên quan

Chủ Đề