Its possible to have a generic ArrayList of Java arrays

1. Introduction

We may wish to use arrays as part of classes or functions that support generics. Due to the way Java handles generics, this can be difficult.

In this tutorial, we'll understand the challenges of using generics with arrays. Then, we'll create an example of a generic array.

We'll also look at where the Java API has solved a similar problem.

Array List and Generic Array List in Java

ArrayList is a data structure that can be stretched to accommodate additional elements within itself and shrink back to a smaller size when elements are removed. It is a very important data structure useful in handling the dynamic behavior of elements.Technically speaking, java Array List is like a dynamic array or a variable-length array. Now it is not type safe so typecasting is required at runtime.

Let us see and understand the following code that will help you work around with Array List.

ArrayList a = new ArrayList(); // Non Generic Array

We can import ArrayList by import java.util.ArrayList

Generic Array In Java

If you have defined a generic array, then the component type will not be known at runtime. Thus it is not advisable to define arrays as generic in Java.

A Generic Array definition is as shown below:

E [] newArray = new E[length];

The compiler does not know the exact type that is to be instantiated as the type information is not available at runtime.

So instead of arrays, whenever generics are required, you should prefer the list component of the Java Collections framework.However, you can create generic structures that are array-like using object array and reflection feature of Java.

These two approaches that allow us to define arrays of different data types are explained below in detail.

Create And Initialize The Generic Array

In this section, let’s create an array-like structure that is generic in nature. Using these structures, you will be able to create arrays by providing the data type as an argument.

Using Object Array

This approach uses the array of type Objects as a member of the main array class. We also use get/set methods to read and set the array elements. Then, we instantiate the main array class that allows us to provide the data type as required.

This simulates the generic array.

The following program demonstrates the use of object array to create a Generic array-like structure.

import java.util.Arrays; class Array<E> { private final Object[] obj_array; //object array public final int length; // class constructor public Array(int length) { // instantiate a new Object array of specified length obj_array = new Object [length]; this.length = length; } // get obj_array[i] E get(int i) { @SuppressWarnings("unchecked") final E e = (E)obj_array[i]; return e; } // set e at obj_array[i] void set(int i, E e) { obj_array[i] = e; } @Override public String toString() { return Arrays.toString(obj_array); } } class Main { public static void main(String[] args){ final int length = 5; // creating integer array Array<Integer>int_Array = new Array(length); System.out.print("Generic Array <Integer>:" + " "); for (int i = 0; i < length; i++) int_Array.set(i, i * 2); System.out.println(int_Array); // creating string array Array<String>str_Array = new Array(length); System.out.print("Generic Array <String>:" + " "); for (int i = 0; i < length; i++) str_Array.set(i, String.valueOf((char)(i + 97))); System.out.println(str_Array); } }

Output:

Its possible to have a generic ArrayList of Java arrays

The answer cannot be simple as both offer some unique features for java developers. It would be a subjective decision based on the requirements of a problem.

Following are 10 points discussing the features offered by an Array and ArrayList and the differences between them. This can help you build a better perspective on the Array vs Arraylist in java debate and provide you with an insightful understanding of the proper use of each of them.

1. Static VS Dynamic Nature:

As already mentioned above, the fundamental difference between Array vs Arraylist is in their nature. Both Array and Arraylist exhibit different natures for storage. When an array is made, the memory is allocated at compile time and the developer would have no control during runtime. On the contrary, Arraylist is based on the practicality of the list data structure. It mimics the features of a list which is a dynamic data structure, thus it has the same nature. It gives an edge to ArrayList as it would be a better choice when it comes to solving dynamic problems.

2. Fixed vs Variable Length:

The one difference between Array and ArrayList in Java that every developer surely knows is that Array is a fixed-length data structure while ArrayList is a variable-lengthCollection class. It means that once an array is declared with a certain size, it is fixed and you cannot change it. Whereas, ArrayList automatically re-sizes itself when it gets full depending upon the capacity and load factor. In retrospect, an ArrayList’s capacity grows automatically as new elements are added in it.

The fixed size is the only limitation in arrays. Thus, ArrayList would be a clear choice for developers who are uncertain about the frequency of data at compile-time and want to specify the size at runtime. Despite that, an experienced developer would know how significantly it impacts the performance of the program. However, an ArrayList cannot be a good choice in every situation, especially when there are frequent changes to be made in the size of the ArrayList.

3.Type-safety and generic Support:

Developers can easily ensure type-safety in java using Generics. Another difference in the Java Array vs ArrayList debate is that Arrays do not allow the use of Generics. An Array is a homogeneous data structure; therefore it contains data specific data type. As the data type is already defined in an Array instance, it knows which data it can hold and throws an exception labelled “ArrayStoreException” in the case of someone attempting to assign a different data type in an array that is not convertible into that data type of Array.

For example, here is a code snippet showing when we will automatically encounter an ArrayStoreException.

1. String temp[] = new String[2]; // an array of string data type is declared 2. temp[0] = new Integer(12); // it will throw ArrayStoreException due to trying to add Integer object in the array.

Since ArrayList is a class, it allows you to use Generics to ensure type-safety. Without using Generics, objects with different data types can be assigned in an ArrayList. This can cause irregularities and will not generate any error even if there is unintentional use of distinct data types. Such an error could be easily missed out by the developer and would have to be handled during quality assurance testing.

Here is an example,

1. List list = new ArrayList(); 2. list.add(5); 3. list.add("5"); // It will not generate any error 4. //With Generics, it is required to specify the type of object we need to s ore. 5. List<Integer> list = new ArrayList<Integer>(); 6. list.add(5); 7. list.add("5");// It will generate a compile-time error

4.Dissimilar Methods:

Array and ArrayList can also be differentiated based on the radically different methods offered by both of them, for instance,in calculating the length of Array or the size of ArrayList. Array provides a variable that denotes the length of Array, while ArrayList has a size () method in java that calculates and returns the size of ArrayList. Another example would be that Java provides an add () method to insert an element into ArrayList, whereas for storing an element in Array, it simply requires the use of an assignment operator.

A unique advantage that arraylist offers is that the same add () method can also insert a specific value at a certain position, moving all the values ahead by one. But this will require you to write some lines of code if you want to do it using a standard array.

See the code snippet mentioned below,

1. int arr [] = new int[3]; 2. arrayLength = arr.length ; //the length of the array will be assigned to the variable arrayLength 3. arrlist = new ArrayList(); 4. arrlist.add(12); 5. arrlist.size(); //it will return 1 as only 1 element has been added in arraylist.

5.Type of elements to be stored:

Another point in Array vs ArrayList is that ArrayList cannot contain primitive data types (like int, float, double), it can only contain Objects. In comparison, Array can store both primitive data types as well as Objects in Java.

There is a method called “Autoboxing” that allows storing primitive data types in ArrayList but it merely gives an impression of it. It simply converts the data into an Object before storing it in an ArrayList.

For instance, suppose we have ArrayList called “arrList”,

1. arrList = new ArrayList(); 2. arrList.add(23); // attempt to add 23 (an integer value) in arraylist. Although it seems like storing an integer in arraylist but it will be converted into an object before storing.

Using Autoboxing, JVM implicitly converts the primitives to equivalent objects, ensuring that only objects are added into an ArrayList. Thus, the above step works like this:

ArrayList object.add( new Integer(23)); // Converted int primitive into an Integer object and then it is added to arrList.

6.Different declarations:

Both Array and ArrayList have a very different declaration process. As Array has a fixed variable length, it needs to specify the size at the time of declaration along with the data type.

int[] numbers = new int[10];On the contrary, ArrayList can be easily declared without specifying the size or datatype, as Java will create ArrayList with the default size and it can later be resized as per requirement.ArrayList<Integer> numList = new ArrayList<Integer>();

7.Array is Multi-dimensional:

The array is commonly known for multi-dimensions. one dimensional (1D), two dimensional (2D) even three dimensional (3D) arrays can be declared for storing various types of data. On the other hand, ArrayList is always single dimensional. Arraylist is based upon the properties of a list due to which it does operate beyond one dimension.

8.Different Iteration processes:

ArrayList class offers an iterator to iterate through the elements in a declared ArrayList, whereas a loop is used (mainly FOR loop) to iterate through arrays whether it is a single or multi-dimensional array. Using FOR loop could give more control if applied with a proper counter as compared to an iterator.

9. Performance:

Performance is one of the most important aspects to be considered while comparing Array vs ArrayList in java. It can significantly affect the decision of a developer while choosing between an Array or ArrayList to implement in a program.

In terms of performance, both Array and ArrayList would provide similar performance when considering the time taken for adding or retrieving the elements if you know the index. However, this is the only point where performance is the same.

Although ArrayList seems faster, overall, it does not amount to much difference.. Internally, an ArrayList is made using Arrays in Java, and all resize operations involve creating another array with a new size, transferring all the data into that implicitly and then renaming the newly created Array. This frequent memory allocation process is expensive and can significantly affect performance if you are dealing with a lot of data.

Methods like resize () and add () could slow down the program if they are used frequently with a lengthy ArrayList. In that case, if you want to use ArrayList, try to keep the use of resizing methods to a minimum or use Array instead. Creating an array of a bigger size at compile time could be a better option instead of frequent memory allocations in ArrayList.

10. Usability:

Though ArrayList can be slower than standard arrays in terms of performance, it is easier to implement than Arrays. The flexibility with length, dynamic nature and implicit processes for resizing makes it simpler and easy to develop logic, especially for new developers. Where an operation can be performed by just a single method in ArrayList, it requires multiple lines of codes to be written for implementing it using an array.