ICOM 4035 – Data Structures

Fall 2007


Laboratory 2: Programming with generics


1.    Objectives


  1. Use generics to reuse code.
  2. Make a collection to store any kind of data.
  3. Use exceptions to control errors in a program.


2.    Overview


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>


            E data;



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.


public SomeName()





Generic arrays are declared in the following manner:

E[] anArray = (E[])(new Object[10]);

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>






3.    Practice


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.