ICOM 4035 – Data Structures
Laboratory 2: Programming with generics
It is a good programming practice to make our code able to be used in multiple applications. As C++ provides templates to make a code the same for different data types, Java has the generics. The syntax of the generics goes as follows:
public class SomeName<E>
After adding <E> to the class definitions we are specifying that the class is generic and that the field data can be of any type. To declare this object one has to add the <E> to the declaration.
SomeName<int> myVar = SomeName<int>();
In the above example myVar is type SomeName and internally the field called data is of type int. Although the call of the constructor has the <int> added the definition of it doesn’t require it.
Generic arrays are declared in the following manner:
E anArray = (E)(new Object);
If we want to make a code that sorts a collection using the method compareTo then we need to guarantee that the type of E has the method compareTo defined. This is ensured using the following definition:
public SomeSorter<E extends Comparable>
In this laboratory you are asked to implement an interface called ArrayList which has the methods necessary to create a collection of generic array. You will implement this interface with the object DynamicArrayList.
DynamicArrayList is an object based internally in a generic array (E). This ArrayList is Dynamic, meaning that when a limit of capacity is reached, more capacity is added instead of throwing an exception.
Download Lab2.tar.gz here.