Bill Teter
Office:          149 Redcay
Telephone:    2782
Office Hours:  Tuesday, Thursday 9:00-12:00

email:  william.teter@plattsburgh.edu

       

 

Lab 6*  Comparable interface and a Generic Sorted List

In this lab you will create a class called SortedArrayList that is like an ArrayList but keeps elements in sorted order as they are added.  Elements must be Comparable.  The SortedArrayList class should make use of java's generic syntax to allow adding only objects of type <AnyType>.  Your SortedArrayList class will have the following methods:  size, get, add,  and remove.

Start by copying all the files from my public directory into a directory in your account called lab6.  My directory is:

/home/teterwa/public/csc223/lab6

The class SortedArrayList is very much like the GenericSimpleArrayList class discussed in class and in our Text.  The current add() method places entries at the end of the list after it checks for need to resize the array.  You will modify add() so that it adds entries in proper order by using the compareTo() method.  Do this is two steps.  First, write a for loop that finds the index at which the new item should be placed.  The second step is to move all values down one slot in the array with a for loop that starts at position size and works back up the array.  Finally the new element is assigned in the proper position.

Test your Sorted Array class with the TestString program that copied.  It is run with a single command line argument that names a text file.  You can try d0, d1, d2, d3.  

For the second part of the assignment create a Person class with a name field and an int age field.  This class should implement Comparable<Person> interface based on a person's age.  Create a TestPerson class that creates a SortedArrayList of Person, creates the three persons:

        Person p1 = new Person("sam",33);
        Person p2 = new Person("john", 13);
        Person p3 = new Person("anne", 20);

Add the three persons to the Sorted ArrayList and then print them out.

Some suggestions and clarifications
    Anytime a class tries to use generics with an array field warnings are inevitable from the compiler because castes are essential.  With this in mind make the SortedArrayList class a simple generic with no reference to Comparable.  That is:
    public class SortedArrayList <AT>{