Week 111 — What is the difference between arrays and `List`s?

Question of the Week #111
What is the difference between arrays and Lists?
13 Replies
kali
kali4w ago
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.
int[] numbers = new int[5]; // create an array storing 5 ints
numbers[0] = 1;

String[] strings = new String[3];//create an array storing 3 Strings
strings[0] = "Hello";
strings[1] = "World";

for(int i=0; i<strings.length; i++) {
System.out.println(strings[i]);
}
int[] numbers = new int[5]; // create an array storing 5 ints
numbers[0] = 1;

String[] strings = new String[3];//create an array storing 3 Strings
strings[0] = "Hello";
strings[1] = "World";

for(int i=0; i<strings.length; i++) {
System.out.println(strings[i]);
}
kali
kali4w ago
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.
List<String> data = new ArrayList<>();//create an empty ArrayList
data.add("Hello");
data.add("World");
data.add("Goodbye");
data.remove(2);//remove the element at index 2

for(int i=0; i<data.size(); i++) {
System.out.println(data.get(i));
}
List<String> data = new ArrayList<>();//create an empty ArrayList
data.add("Hello");
data.add("World");
data.add("Goodbye");
data.remove(2);//remove the element at index 2

for(int i=0; i<data.size(); i++) {
System.out.println(data.get(i));
}
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:
List<String> immutableData = List.of("Hello", "World");//create an immutable List with two elements
List<String> otherImmutableList = List.copyOf(data);//create an immutable copy of data
System.out.println(immutableData.getFirst());//reading data from immutable Lists is allowed
//immutableData.add("modifying immutable List is not allowed");//UnsupportedOperationException
List<String> immutableData = List.of("Hello", "World");//create an immutable List with two elements
List<String> otherImmutableList = List.copyOf(data);//create an immutable copy of data
System.out.println(immutableData.getFirst());//reading data from immutable Lists is allowed
//immutableData.add("modifying immutable List is not allowed");//UnsupportedOperationException
Similar to immutable Lists, unmodifiable Lists 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<String> dataView = Collections.unmodifiableList(data);
//dataView.add("Hi");//UnsupportedOperationException
data.add("another element");
System.out.println(dataView.getLast());
List<String> dataView = Collections.unmodifiableList(data);
//dataView.add("Hi");//UnsupportedOperationException
data.add("another element");
System.out.println(dataView.getLast());
Lists 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
kali
kali4w ago
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
kali
kali4w ago
There are many basic differences between array and list
kali
kali4w ago
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
kali
kali4w ago
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
kali
kali4w ago
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.
kali
kali4w ago
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:
int[] array1 = new int[0]; // declares an empty array of ints (primitive type)
array1[0] = 10; // runtime ERROR: the access to the 1st element is impossible because the array is empty!
int[] array1 = new int[0]; // declares an empty array of ints (primitive type)
array1[0] = 10; // runtime ERROR: the access to the 1st element is impossible because the array is empty!
Example 2 - with primitives :
int[] array2 = new int[2]; // declares integer array with 2 elements, both initialized at 0.
System.out.print(array2[-1]); // runtime ERROR. Accessing with a negative index number !
System.out.print(array2[2]); // runtime ERROR: Accessing with an index number that doesn't exist, the last index available is 1.
array2[0] = 123; // assigning a new value to the 1st element.
array[1] = array[0]; // copying the value of the 1st element into the 2nd one.
System.out.print(array[0]); // outputs 123
System.out.print(array[1]); // outputs 123
int[] array2 = new int[2]; // declares integer array with 2 elements, both initialized at 0.
System.out.print(array2[-1]); // runtime ERROR. Accessing with a negative index number !
System.out.print(array2[2]); // runtime ERROR: Accessing with an index number that doesn't exist, the last index available is 1.
array2[0] = 123; // assigning a new value to the 1st element.
array[1] = array[0]; // copying the value of the 1st element into the 2nd one.
System.out.print(array[0]); // outputs 123
System.out.print(array[1]); // outputs 123
Example 3 - with objects :
Object[] array1 = new String[1]; // valid
Animal[] array2 = new Dog[3]; // valid while Animal is a supertype to Dog
String[] array3 = new Object[0]; // invalid
Object[] array1 = new String[1]; // valid
Animal[] array2 = new Dog[3]; // valid while Animal is a supertype to Dog
String[] array3 = new Object[0]; // invalid
Example 4 - with objects :
String[] array = new String[2]; // array of String objects, with 2 cases and ready for use.
System.out.print(array[0]); // outputs "null"
array[0] = "Hello"; // Assigning a "Hello" string to the 1st case in the array
array[0] = "World"; // replacing the "Hello" string with another one, "World".
String[] array = new String[2]; // array of String objects, with 2 cases and ready for use.
System.out.print(array[0]); // outputs "null"
array[0] = "Hello"; // Assigning a "Hello" string to the 1st case in the array
array[0] = "World"; // replacing the "Hello" string with another one, "World".
It's possible to declare an array in java without explictly indicating the type in the right side of the statement :
java
String[] array = {"Hello", "World"};
java
String[] array = {"Hello", "World"};
kali
kali4w ago
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 :
List<Integer> list = new ArrayList<>(2); // declares an empty list with an initial capacity !
list.add(10); // adding a new value(10), the list's size becomes 1
list.add(20); // adding a new value (20), after the 1st one. The list's size becomes 2
list.remove(0); // valid, the list now only have (20) and its size becomes 1
System.out.print(list.get(0)); // outputs 20
List<Integer> list = new ArrayList<>(2); // declares an empty list with an initial capacity !
list.add(10); // adding a new value(10), the list's size becomes 1
list.add(20); // adding a new value (20), after the 1st one. The list's size becomes 2
list.remove(0); // valid, the list now only have (20) and its size becomes 1
System.out.print(list.get(0)); // outputs 20
Example 2:
List<Object> list = new ArrayList<String>(); // ERROR. it's not like array!
List<int> list2 = new ArrayList<>(); // ERROR. it's not like array!
List<Object> list = new ArrayList<String>(); // ERROR. it's not like array!
List<int> list2 = new ArrayList<>(); // ERROR. it's not like array!
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...
kali
kali4w ago
Conversion between Array and List Java provides some built-in tools to convert arrays into lists and vice-versa :
String[] array = new String[3];

List<String> list = Arrays.asList(); // converting array to list
array = list.toArray(new String[0]); // converting list to array
String[] array = new String[3];

List<String> list = Arrays.asList(); // converting array to list
array = list.toArray(new String[0]); // converting list to array
⭐ Submission from firasrg5942
kali
kali4w ago
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:
int[] numbers = new int[20];
int[] numbers = new int[20];
... 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:
numbers[3] = 1_000;
numbers[3] = 1_000;
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:
List<Integer> numbers = new ArrayList<>(20);
List<Integer> numbers = new ArrayList<>(20);
... 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:
numbers.add(1_000);
Integer first = numbers.get(0);
numbers.add(1_000);
Integer first = numbers.get(0);
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:
List<Integer> numbers = new ArrayList<>(20);
numbers.get(0); // 1. Exception
numbers.add(1, 1_000); // 2. Exception
numbers.add(0, 1_000); // 3. Valid
numbers.set(0, 2_000); // 4. Valid
List<Integer> numbers = new ArrayList<>(20);
numbers.get(0); // 1. Exception
numbers.add(1, 1_000); // 2. Exception
numbers.add(0, 1_000); // 3. Valid
numbers.set(0, 2_000); // 4. Valid
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.
kali
kali4w ago
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
kali
kali4w ago
Submission from mercy_17083

Did you find this page helpful?