CS401 Lab 8 : Using Generics


Introduction

Last week, we discussed the new Generic syntax of the Java language that allows the compiler to enforce type safety in classes. We saw that the <> symbols are used in the class header to signify that the class uses a generic type that the user will supply at compile time. For example, from the Java API, we have:

public interface List<E>
{
	void  add(E x);
	void  add(int index, E element);
	E     remove(int index);
	E     get(int index);
	...
}

The generic type, 'E', is used as a placeholder for the actual type that will be used when a List is created. Thus, we we create an instance of List<String>, the method signatures become void add(String x), void add(int index, String element), String remove(int index), and String get(int index). In this lab, you'll alter the SimpleDeque class from Lab 7 to use this new syntax.


SimpleDequeT

Create a new generic interface, called SimpleDequeT, from the SimpleDeque interface of Lab 7. Change the method declarations to use the type parameter as the List interface does above.

MyDequeT

As before, you now have to create a class that implements this generic interface:

public class MyDequeT<T> implements SimpleDequeT<T>
{
	private T[] data;
	private int count;

	public MyDequeT(int max)
	{
		data = (T[]) new Object[max];
		count = 0;
	}
	...
}

Notice that this class, itself, is also a generic class that implements the SimpleDequeT interface with the same type parameter. As before, the rest of the class is left for you to implement using the type parameter where needed.

Lab8

The Lab8.java file below is missing two methods for you to implement, printDequeFront and printDequeRear.


Program

Download the Lab8.java file below, implement the two missing methods, and compile it with your SimpleDequeT and MyDequeT classes. The output should be the same as that from Lab 7.

Lab8.java

Output:

javalab>java Lab7
Queue adds at rear and removes at front
0 1 2 3 4

Queue adds at front and removes at rear
0.0 2.0 4.0 6.0 8.0 10.0 12.0 14.0

Stack adds and removes at rear
Marge Ingmar Ingrid Bertha Herb