11.2 List Class | 529
We can implement this algorithm without having to know anything about the list. We
just use the instance methods supplied in the interface.
public booleanisDuplicate(List list1, List list2)
// Returns true if the lists are identical
{
if (list1.length() != list2.length())
// Number of items is not the same
return false;
else
{
String next1; // An item from list1
String next2; // An item from list2
int counter = 1; // Loop control variable
booleansame = true; // True if lists are equal
int limit = list1.length(); // Number of items in list
list1.resetList(); // Set up for iteration
list2.resetList();
while(same && counter <= limit)
{
next1 = list1.getNextItem(); // Get an item from list1
next2 = list2.getNextItem(); // Get an item from list2
same = next1.compareTo(next2) == 0;
counter++;
}
}
returnsame;
}
This method was included in the following driver, which was run twice with two different
versions of list1.dat. We can write this driver without knowing anything about the list’s im-
plementation. All we have to do is import the package list, where the class Listis stored.
importlist.;
importjava.io.;
public classListDriver
{
public static voidmain(String[] args) throwsIOException
{
BufferedReader inFile;
BufferedReader inFile2;
inFile = new BufferedReader(new FileReader("list1.dat"));
inFile2 = new BufferedReader(new FileReader("list2.dat"));
// Instantiate the lists
List list1 = new List(20);