Lab on Java generic types; exceptions
You may work in pairs on this lab.
Write a generic class Set with a type parameter T. The class uses an
array of 100 elements of type T (initially just storing all NULL
values). The class supports the following operations:
Test your code to create a Set of Strings (<String>Set) and a
Set of Integers. Do not cast the elements returned by find - generic
types don't require typecasting.
void insert(T elt) - inserts an element into the
set. An element is inserted into the first empty spot in the
array. For now don't worry about the array being full - just do
nothing if you can't insert an element. Also, don't worry about
duplicate elements - just insert them.
- - delete an element equal to
elt (use the
equals method to determine
T find(T elt) returns the first element equal to
elt, as determined by
Can you insert a String into a Set of Integers? Explain what happens
when you try.
Write an exception SetOverflow that gets thrown in insert method when
the array is full. Write a try/catch block in your testing code to
test the exception. The exception must extend Exception class, not
Write an equals method for a Set class (two sets are equal if their
arrays contain equals elements in the same order). Can you use
instanceof T in your equals method? Why or why not? Use
the equals methods of the elements to compare them.
Change the Set implementation so that it stores elements in the
increasing order. In this implementation equal elements should be
inserted only once. The implementation doesn't have to be efficient -
you may shift all elements when inserting a new one. Note that in this
case the class only works for Comparable elements, so in the class
declaration you need to say
Comparable>. Check that the only objects you can use it with
are those implementing Comparable interface.
Submit all you code, write answers to questions in comments.
Eclipse supports for Java generics, so you can get meaningful error
messages related to generics. Make sure that Eclipse is set to Java
CSCi 4651 home page
The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.