Array Worksheet
Array Worksheet
Exercise 1
Create a new Java project (call it Array) and in this project create a new class called Dog which
implements the Comparable interface and has the attributes and methods shown below.
You have probably not used the toString and compareTo methods before so here is the code for
these 2 methods.
BEFORE continuing ensure that your code is syntactically correct – if you have any errors or
warnings that you cannot resolve then ask!
The toString and compareTo methods are ‘special’ compared with the others we have created and
this can be seen in the Eclipse IDE.
In your project create a class called Test001 and inside the class enter the following code.
System.out.println(d1);
System.out.println(d2);
}
Experiment 1
Run the program and notice what is displayed in the output window? Compare the output to the
Dog class, are there any conclusions that can be made? Not sure, then comment out the toString
method and run the program again any difference?
Experiment 2
Modify the method so that it looks like this
public static void main(String[] args) {
Dog d1 = new Dog(new Long(56498), "Fido");
Dog d2 = new Dog(new Long(34999), "Rover");
System.out.println(d1);
System.out.println(d2);
if(d1.compareTo(d2) == 0)
System.out.println("Same doggy");
else
System.out.println("Different doggy");
}
Change the name of d2 to Fido and run the program again. Do the dogs match?
Experiment 3
Change the name of d2 back to Rover and its chip ID to 56498 and run the program again. Do the
dogs match?
Experiment 4
Change the Dog class so that dogs with the same name match.
Describe in your own words the rules for implementing the compareTo method.
Why is the toString method useful?
Include the code for the compareTo method you created in experiment 4.
What is the difference between Long and long and what similar cases can you find?
public Test002()
{ long id;
for(int i = 0; i < NO_DOGS_IN_POUND; i++)
{ id = Math.abs(rnd.nextInt()) %
RANGE; dogPound[i] = new Dog(id, "");
}
for(int i = 0; i < NO_REPORTED_LOST; i++)
{ id = Math.abs(rnd.nextInt()) %
RANGE; reportedLost[i] = new Dog(id,
"");
}
}
time = System.currentTimeMillis();
for(int i = 0; i < NO_REPORTED_LOST ; i++){
if(search(reportedLost[i]))
nbrFound++;
}
time = System.currentTimeMillis() - time;
time = System.currentTimeMillis();
for(int i = 0; i < NO_REPORTED_LOST ; i++)
{ if(Arrays.binarySearch(dogPound, reportedLost[i]) >= 0)
nbrFound++;
}
time = System.currentTimeMillis() - time;
performSequentialSearch();
pause(100);
pause(100);
performBinarySearch();
}
Once you have entered this program run it and study the output. Comment out the line in yellow and
run the program again study the output.