Week 111 — What is the difference between arrays and `List`s?
Question of the Week #111
What is the difference between arrays and
List
s?13 Replies
Arrays allow storing a given number of elements of the same type in a variable. The number of elements to store is set when an array is created and cannot be changed afterwards. It is possible to replace elements of an array but adding and removing elements is not possible. Array elements can be accessed using square brackets with the index (starting at 0) identifying the element being written inside the square brackets.
On the other hand,
List
is a general interface for data that can be accessed via indices.
The most common implementation of this interface is ArrayList
which is based on arrays but allows adding and modifying elements by creating new arrays when necessary.
Another implementation of the List
interface is LinkedList
which can be accessed in the same way as ArrayList
but is based on a doubly-linked list.
In addition to that, it is possible to create an immutable List
which cannot be modified in any way:
Similar to immutable List
s, unmodifiable List
s do not allow any modifications on them but actually represent a view on another List
. Any change to the backing List
is propagated to the unmodifiable List
:
List
s cannot hold primitive elements but primitive wrapper classes like Integer
can be used to store values of primitives using a List
.📖 Sample answer from dan1st
Arrays are of fixed size and homogenous type (it can take only one data type of value). They occupy therefore a fixed memory location and are faster to work with.
Lists can be appended as much as wanted after creation. They may be homogenous or heterogenous and are typically slower than arrays.
In Java arrays come inbuilt in the java.lang while you have to import from java.util to use lists.
Submission from bhavraj
There are many basic differences between array and list
Generally,
Arrays are best when you know the size in advance and need fast access and low overhead.
Lists are better for cases where you need flexibility in adding, removing, or modifying elements dynamically.
Submission from h_s_j_1107_83351
The difference is arrays has a static size of memory allocation, when you instantiate an arrays you should define a size, on the other hand List works with dynamic memory allocation and you should not define a size when your instantiate
Submission from gustavohmf8291
Arrays and Lists are are fundamental, indexed data structures in many programming languages. They are NOT specific to Java 🧑💻 . Personally, I've been using arrays extensively during my early years of learning, they were perfect in helping me to understand algorithms, without much complexity. But, as I progressed with the time, and discovered the Collections Framework (starting with Vector 😆 ), I realized that this module is very important to know,, notably, when dealing with Object-Oriented challenges. IMO, Lists offers significant advantages over arrays in some areas, such as strong typing, dynamic resizing, and built-in operations like add/delete/replace. As for arrays, they are helpful to make a read-only sequence of objects or when having 2/3 dimensions (I believe there are some other cases where arrays are more useful than collections).
Pro Tip: *both arrays and lists are valuable tools , they share a common capability of storing objects, they have different nature and usecases, they aren't equivalent! They use indexes starting from zero. You have to use them carefully. You might get confused between them at some levels, do mistakes, but learn ! *
Data structure
In computer science, a data structure is a data organization and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data, i.e., it is an algebraic structure about data.
Arrays
A data structure with a fixed size that can store primitives or objects, all sharing the same type. In case of using objects, we can assign a subclass to a supertype. Arrays are faster in performance when reading values but not while inserting/updating.
Example 1 - with primitives:
Example 2 - with primitives :
Example 3 - with objects :
Example 4 - with objects :
It's possible to declare an array in java without explictly indicating the type in the right side of the statement :
Lists
A data structure with a dynamic size, that can store objects only. The List API is part of the Java Collections Framework. List is an interface. ArrayList is an implementation of List, and it is a common class used between Java developers.
IMPORTANT ⚠️ : ArrayList doesn't mean Array! It just has the "Array" in its name. Also, ArrayList, has an interesting feature called initialCapacity which helps to improve performance.
Example 1 :
Example 2:
Stack Overflow
What's meant by parameter (int initial capacity) in an arraylist
What's meant by parameter (int initialCapacity) in an ArrayList, I thought it's the number of elements but it didn't work when I did this:
public class MyClass {
private ArrayList<Integer&g...
Conversion between Array and List
Java provides some built-in tools to convert arrays into lists and vice-versa :
⭐ Submission from firasrg5942
In Java, arrays are a fixed-size collection of primitives or objects. The JVM allocates the space needed for all elements of the array at the time it's created. For instance:
... will create an array of 20 integers, with all elements initialized to
0
. Similarly, an array of objects will initialize all elements to null
.
Elements of an array can be accessed using subscript notation with the 0-based index:
The code above will set the fourth element of the array to the value 1000
. Attempting to access an element with an index < 0 or >= array length will result in an exception. The length of the array can be read using the .length
property.
Arrays have a fixed size, which means they cannot be extended beyond their original size. If a larger array is needed, a new one must be created and all elements of the old array copied into it using the System.arraycopy()
method.
On the other hand, the List
interface defines a dynamically-sized collection of objects (primitives are not allowed, though boxed primitives are). For instance:
... will create a list of Integers
with an initial capacity of 20 items. Note that in the case of Lists
, "capacity" is different from "size". In the example above, the ArrayList
will allocate an underlying array with a size of 20. However, the size of the List
is 0, because no elements have been added to it.
Elements of a List
can be accessed using methods that accept an index as a parameter. As with arrays, indexes are 0-based:
The code above will set the first element of the List
to the value 1000
(auto-boxed to an Integer
), and then retrieve that element and assign it to first
. As with arrays, attempting to access an element with an index < 0 or >= list size will result in an exception. The current size of the List
can be accessed using the size()
method.
Lists
have a dynamic size, which means they grow or shrink based on the number of elements.
Another difference with arrays is that Lists
cannot be "sparse" -- an index is not valid until a value (even null
, if supported by the implementation) has been assigned to it. The code below will result in an exception:
The size of the new List
is 0, so line 1 would throw an exception. Retrieving an index >= size is not allowed. Similarly, line 2 would throw an exception, because adding a value with index > size is not allowed. Items can be added to the end of the List
or "inside" it, but not past the end. Line 3 is valid because it adds the first element to the list. Line 4 is valid because it changes an existing element.Generally,
Lists
are more useful and easier to use than arrays, and so are more common in "regular" code. However, arrays have an advantage in terms of speed and size, so they will generally be used for performance-sensitive tasks like I/O buffers.⭐ Submission from dangerously_casual
Submission from mercy_17083