Array and ArrayList | Preparing for Java Oracle Associate Certification (OCA) / Java basic technical tests

Arrays are a very important structure in a programming language. In this article I’ll talk about arrays ([ ]) and ArrayList as part of the Java Oracle Certified Associate (OCA) exam. Other collections are part of the topics for OCP exam so I’ll cover them in my series of post about that exam. Make sure to subscribe so you don’t miss is!

This series of articles are meant for people who already know the basics of Java, that is grammar and vocabulary, and knowledge of OOP. The topics covered correspond to OCA Programmer I level and relate to Java 8 version. If you need to learn the basics, I can recommend the JetBrains Academy Java developer track.

Arrays

Java has two types of arrays: dynamic and fixed size. What we usually refer to as “array” is the fixed size type, declared as Type[ ] arrayName.

First, it’s super important to know all the ways the arrays can be declared/instantiated (list is not exhaustive):

int [] numbers = new int[3]; /*length (3) must be set from start when instantiating even an empty array; the array is filled with the default value corresponding to the type, so in this example the array is filled of 0 (zero)*/

int numbers [] = new int [] {1,2,3}; /*this sets an array of length 3 containing values 1 2 and 3*/

int numbers [] = {1, 2, 3}; /*this simplified instantiation does the same as previous line, but please note it only works as inline declaration*/

int []a, b = int []a, int b[];
int a[], b = int a[], int b;

Arrays are reference types, thus:

  • Arrays are nullable: if they’re not instantiated, the reference points to null.
  • Using the equals() method on an array would compare the references of the two arrays, not its content.

Arrays have a public property called length, which is not to confuse with length() method of String class e.g.

Sorting arrays

There is an utility class java.util.Arrays that offers some static ready-to-use methods (don’t forget import or use whole classpath).

Arrays.sort(array) modifies the array and returns void. If the array contains String objects, they’re sorted alphabetically (numbers before letters). If it contains custom type objects the associated behavior (might be the default Object method or the overridden version) is used.

Searching arrays

Arrays.binarySearch(array, searchedElement) returns the index or the negated value of the index where the element should be. Be careful that the array should be sorted, otherwise result is random and not always accurate!

Varargs

Varargs for “variable arguments” is written like Type… name, with no other possible syntax. There can be only one vararg parameter at once and it’s always in the end of the list. It takes a list of arguments of the defined type, not being limited to a certain length.

Two-dimensional / N-dimensional arrays

Or so-called “array of arrays”. The dimension of the containing array is mandatory at assignment. Also know all possible declaration and assignment syntaxes, this list is not exhaustive.

int [][] array;
int array [][];
int [] array [];
int [] array1[], array2[][], array3; // a1 is 2D, a2 is 3D, a3 is 1D

int [][] array = new int[3][2]; // matrix

Integer [][] array = {{1,4}, null, {9,7,8}, {}}; // not a matrix, still legit

int [][] array = new Type[2][];
array[0] = new Type[3];
array[1] = new Type[7];
array[2] = new Type[1]; // NOK because containing array is of size two

int [][] array = new Type [][]{{1,4},{1,3,2}};

ArrayList

I, and every single CS student I think, find plain arrays a pain, especially when they are multi-dimensional. ArrayLists are way easier to use. They have a dynamic size, which is a huge advantage.

The ArrayList class implements AbstractList (which extends AbstractCollection) and implements RandomAccess, Serializable, Cloneable, Iterable, Collection and List. It’s situated at java.util.ArrayList which has to be imported or used with full classpath. Be careful that List and ArrayList are two different imports.

Good practice is to declare a collection with the interface type (it’s even mandatory to use some collections with some APIs and frameworks so better adopt a good habit now), but declaring the concrete type works too. Collections make use of the <generics> type check (diamond notation), which is not mandatory either but a very good practice. Generics are covered in the OCP certification and will thus be part of a future article on the blog.

Here are some declaration and instantiation examples:

List<Type> list = new ArrayList(); // bad practice, triggers a warning but compiles
List<Type> list = new ArrayList<>(); // since Java 7, it's no more mandatory to write the type in the second diamond
List<Type> list = new ArrayList<Type>();
List list = new ArrayList(); // no type check, defaults to Object with maybe some casting to do
List<> list = new ArrayList(); // NOK, empty diamond cannot be used on the left side of an assignment
List list = new ArrayList<>();

ArrayList constructors are:

new ArrayList();
new ArrayList(15); // capacity, different from length and not final, same as StringBuilder
new ArrayList(collection); // instantiates the list with the content of another collection

ArrayList methods

(E represents a reference of a type of any class that the array list can hold)

  • boolean add (E element), which always returns true… (because adding the element succeeded)
  • void add (int index, E element), if list is empty the index can only be 0, otherwise it has to be in the range between 0 and the size; else an IndexOutOfBoundException is thrown

For both methods, if a type was specified in the diamond, additions are type-checked at compile time. Types can be covariant.

  • E remove (int index), returns the removed element
  • boolean remove (Object object), removes first match only and returns true if found
  • E set (int index, E element), returns the replaced element
  • boolean isEmpty()
  • int size(), yeah please remember the method is not called length in collections
  • void clear()
  • boolean contains(Object object), uses equals method (default or custom according to what’s available)
  • boolean equals(Object object), returns true only if the two lists contain the same elements in the same order

Also, the utility Collections (with an s, not to confuse with Collection interface!) provides additional static methods, as Collection.sort(list). The sorting method requires objects in the collection to implement comparable.

Transforming array to ArrayList and vice versa

Object [ ] array = list.toArray(); // written that exact way, no other declaration allowed
int [] array = list.toArray(anArray); // the array passed as parameter is of the declared type; the array in parameter is used if length is sufficient

List<Type> list = Arrays.asList([]);

The last mentioned method is a static method. The array and the ArrayList share the same reference, so changes in one are reflected to the other. And because arrays are fixed-size, adding elements in the ArrayList would throw an error.


Check the previous articles about Java certifications and don’t forget to subscribe to receive new posts!

0 thoughts on “Array and ArrayList | Preparing for Java Oracle Associate Certification (OCA) / Java basic technical tests

Leave a Reply

Your email address will not be published. Required fields are marked *

Don’t miss out!

Receive every new article in your mailbox automatically.


Skip to content