Array & List
Arrays
Arrays are usually fixed size collection of items. An array is a basic data structure that allocates memory that will hold our values.
To push the arrays to the limits and see that an array really allocates memory, try to create array of huge size, like
int[] hugeArray = new int[2000000000]. We should getjava.lang.OutOfMemoryError: Java heap spaceexception with default JVM memory settings.
import java.util.Arrays;
public class ArraysDemo {
public static void main(String... args) {
int[] array = new int[5];
array[0] = 3;
array[1] = 4;
array[2] = 6;
array[3] = 8;
array[4] = 1;
int sum = 0;
for(Integer value : array) {
sum += value;
}
System.out.println(String.format("Sum is %s", sum));
System.out.println(Arrays.toString(array));
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}Here is the output.
Lists
Lists are similar to arrays but they are dynamically expanding. Some languages do not distinguish between arrays and lists. A list implementations are using arrays to store values.
Here is a naive implementation of list. This list resizes the array when all the positions in the array are occupied and user requests to insert another item into a list.
We can use the naive implementation of list now.
Here is what the code above prints.
Here is another example with add, get and remove functions.
Last updated
Was this helpful?