# Comparable Interface

 Site: Saylor Academy Course: CS101: Introduction to Computer Science I (2019.A.01) Book: Comparable Interface
 Printed by: Guest user Date: Thursday, December 7, 2023, 10:51 PM

## Description

Objects that have an ordering are compared using the compareTo() method.

## 1. Comparable Interface

Objects of a class that implements the Comparable interface can be arranged into a particular order. For example, objects of class String, which implements Comparable, can be arranged into alphabetical order. Numeric classes such as Integer or Double implement Comparable and their objects can be arranged into numeric order.

Objects of a class that implements Comparable can be compared to each other to determine which comes first when the objects are arranged in order.

Chapter Topics:

• The Comparable Interface
• compareTo() method
• natural order
• collating sequence
• sorting
• binary search

Question 1:Arrange these strings in order: "orange", "apple", "plum". This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

## 2. Comparable <T> Interface

Answer:"apple", "orange", "plum".This is the order that compareTo() would place the strings.

# Comparable<T> Interface

An interface consists of constants and method declarations. The Comparable<T> interface consists of just one method (and no constants):

 int compareTo( T obj ) Compare the object running obj, which is of type T. Return a negative integer, zero, or a positive integer, when he object running the method is less than, equal, or greater than obj.

T stands for the type of the objects. If the objects are Strings, then T is StringStrings implement the Comparable<String> interface.

If an object is of a class that implements Comparable, then that object is less thanequal, or greater than any object of that class. compareTo() returns an integer to show which of these three relations hold.

Relation   objectA.compareTo( objectB )
objectA Less Than objectB Negative Integer
objectA Equal objectB Zero
objectA Greater Than objectB Positive Integer

Question 2:Does compartTo() tell us enough?If any two objects can be compared, and the result is less than, equal, or greater than is this enough to put a collection of objects in order?

## 3. This is enough to put a collection in order.

Answer:"apple", "orange", "plum".This is the order that compareTo() would place the strings.

# Comparable<String> Interface

StringA is regarded as less than StringB if StringA would be proceed StringB in a dictionary. For example,

Expression
Evaluates to
"apple".compareTo("orange")
Negative Integer
"apple".compareTo("plum")
Negative Integer
"apple".compareTo("apple")
Zero
"orange".compareTo("orange")
Zero
"orange".compareTo("apple")
Positive Integer

Only the sign of the returned integer matters if the return value is not zero. The magnitude of a returned integer does not signify anything.

Memory Aide: think of this as subtraction.

apple - orange will be negative.
apple - apple will be zero.
orange - apple will be positive.

Question 3:Examine the following:String myPet = "Fido" ;
String stray = "Rex" ;

if ( myPet.compareTo( stray ) < 0 )
System.out.println( "Good Dog" );
else
System.out.println( "Bad Dog" );What is printed?

## 4. Integer

Answer:Good Dog

# Integer

Examine the following declarations. They use the wrapper class Integer. An Integer object holds an integer as its data and provides several useful methods for working with integers. Class Integer implements the Comparable<Integer> interface so two Integers can be compared.

Integer minusTen = new Integer( -10 );Integer minusFive = new Integer( -5 );Integer five = new Integer( 5 );Integer ten = new Integer( 10 );Integer fifteen = new Integer( 15 );

Mentally replace "compareTo" with subtraction and do the arithmetic. For example, five.compareTo( ten ) works like five-ten. (But recall that is only the sign of the result that matters.)

What is the result of each of the following?

 five.compareTo( ten ) ten.compareTo( five ) five.compareTo( five ) ten.compareTo( fifteen ) minusFive.compareTo( ten ) minusFive.compareTo( minusTen )

Question 4:Examine the following:Integer five = 5 ;
Integer ten = 10 ;What is the value of:five.compareTo( ten )

## 5. Natural Order

Answer:five.compareTo( ten ) is negative.The declaration of the two Integer variables looks wrong, but they are actually correct. Autoboxing automatically constructs Integer objects for the two primitive integers.

# Natural Order Objects that implement compareTo() can be arranged into a natural order. This order can be visualized as an arrangement of objects from left to right as on a number line.

The strings in the picture are arranged left to right in dictionary order.

If an object A is left of another object B, then

objectA.compareTo(objectB)

is negative. For example, X.compareTo("orange") is negative for all the fruit X left of "orange".

Question 5:What is "grape".compareTo( "banana" );


## 6. Rules for compareTo()

Answer:positive

# Rules for compareTo()

With all objects, compareTo() works the way number comparisons work in ordinary arithmetic. Here are a few rules. Most of these are sensible if you think about numbers. Say that AB, and C are Integers. If A.compareTo(B) > 0 and B.compareTo(C) > 0 then A.compareTo(C) > 0. If A.compareTo(B) == 0 then A.compareTo(Z) and B.compareTo(Z) gives the same result, no matter what Z is. The classes that come with Java follow these rules. If you write a class that implements Comparable, you need to follow these rules. This is not hard to do because most sensible compareTo() methods will do this naturally.

Question 6:Say that X.compareTo(Y)==0.Is it then true that X.equals(Y)?

## 7. Consistency with equals()

Answer:For most classes that implement both methods this is true. But it is possible that it is not true, so check the documentation.The compareTo() method might look only at some instance variables of an object and ignore others. The equals() method might look at different instance variables.

# Consistency with equals()

If you are defining a class and writing its methods, you should probably make sure that this rule (and the previous rules) hold true. But for some classes, there might be several possible ideas of what "equals" means, and the idea picked might not not be consistent with compareTo().

Here is a program that tests some of these ideas:

class TestCompareTo
{
public static void main ( String[] args )
{
String appleA = new String("apple"); // these are two distinct objects
String appleB = new String("apple"); // these are two distinct objects
String berry  = new String("berry");
String cherry = new String("cherry");
String A, B;

A = appleA; B = appleB;
System.out.print(  A + ".compareTo(" + B + ") returns ");
if ( A.compareTo(B) == 0) System.out.println("Zero");
if ( A.compareTo(B) < 0 ) System.out.println("Negative");
if ( A.compareTo(B) > 0 ) System.out.println("Positive");
System.out.println(  A + ".equals(" + B + ") is " + A.equals(B) );
System.out.println();

A = appleA; B = berry;
System.out.print(  A + ".compareTo(" + B + ") returns ");
if ( A.compareTo(B) == 0) System.out.println("Zero");
if ( A.compareTo(B) < 0 ) System.out.println("Negative");
if ( A.compareTo(B) > 0 ) System.out.println("Positive");
System.out.println(  A + ".equals(" + B + ") is " + A.equals(B) );
System.out.println();

A = berry; B = appleA;
System.out.print(  A + ".compareTo(" + B + ") returns ");
if ( A.compareTo(B) == 0) System.out.println("Zero");
if ( A.compareTo(B) < 0 ) System.out.println("Negative");
if ( A.compareTo(B) > 0 ) System.out.println("Positive");
System.out.println(  A + ".equals(" + B + ") is " + A.equals(B) );
}
}

Here is the output of the program. You might want to copy the program to a file and run it with a few more selections for A and B.

apple.compareTo(apple) returns Zeroapple.equals(apple) is trueapple.compareTo(berry) returns Negativeapple.equals(berry) is falseberry.compareTo(apple) returns Positiveberry.equals(apple) is false

If you edit the program and change some of the strings to contain upper case, the program might output mysterious results.

Question 7:(Thought Question: ) Do you think that "APPLE".compareTo("apple") returns zero?

## 8. Comparing Strings

Answer:No. Upper and lower case matter.

# Comparing Strings

Upper case characters are regarded as less than lower case characters. So "APPLE".compareTo("apple") returns a negative integer.

When strings are compared, case-sensitive dictionary order is used. Mostly this means that when two strings of the same case are compared, the one that appears first in the dictionary is less than the other. The technical term for this is lexicographic order. Here are the details:

Rule 1: If A.compareTo(B) == 0, then A and B are the same length (counting all characters, including blanks and punctuation) and each character in A is identical (including case) to the character in B at the same location.

"batcave".compareTo("batcave") == 0"batcave".compareTo("bat cave") != 0

There are more rules on the following pages.

Question 8:Decide which strings, when used with compareTo() return zero.ComparisonZero or Not Zero"bugbear".compareTo("bugbear")"bugbear".compareTo("Bugbear")"Zorba".compareTo("Zorba!")"mushroom".compareTo("mush room")"TOAD".compareTo("TOAD")

## 9. Nearly Same Strings, but Different Lengths

Answer:"bugbear".compareTo("bugbear")zero"bugbear".compareTo("Bugbear")NOT zero"Zorba".compareTo("Zorba!")NOT zero"mushroom".compareTo("mush room")NOT zero"TOAD".compareTo("TOAD")zero

# Nearly Same Strings, but Different Lengths

Rule 2: If string A is a prefix of string B, then A.compareTo(B) < 0.
If string B is a prefix of string A, then A.compareTo(B) > 0.

"bat".compareTo("batcave") < 0"apple".compareTo("applesauce") < 0"BAT".compareTo("BATCAVE") < 0"batcave".compareTo("bat") > 0"applesauce".compareTo("apples") > 0"BATCAVE".compareTo("BAT") > 0

In using this rule you need to pay attention to case. "BAT" is not a prefix of "batcave".

There are yet more rules.

Question 9:Decide on the value returned by compareTo():ComparisonZero, Negative, or Positive"bugbear".compareTo("bugbear")"bug".compareTo("bugbear")"pepper".compareTo("peppermint")"toadstool".compareTo("toad")"cat".compareTo("caterpillar")

## 10. First Differing Pair of Characters

Answer:"bugbear".compareTo("bugbear")zero"bug".compareTo("bugbear")negative"pepper".compareTo("peppermint")negative"toadstool".compareTo("toad")positive"cat".compareTo("caterpillar")negative

# First Differing Pair of Characters

The remaining case is the difficult one. Say that two strings are not identical, and one is not the prefix of the other. Then there must be at least one character in one string that is different from a character at the same position in the other string:

first differing characters are 'a' and 'e'beat         |              beet first differing characters are 'r' and 'h'   bear rug     |          bear hugfirst differing characters are 'c' and 'm'batcave   ||||          batmobilefirst differing characters are 'b' and 'B'baseball bat    |    |       baseBall hat

Find the first pair of differing characters. The result of compareTo() is based on just that pair.

Rule 3: Find the first differing pair of characters in the strings A and B. Call them Achar and Bchar. Then A.compareTo(B) is negative if Achar comes before Bchar in the alphabet that Java uses (and otherwise is positive).

This rule compares just two characters. For characters of the same case, the one that comes earlier in the alphabet that Java uses is less than the other. For characters of different case, all upper case characters are less than all lower case characters.

The lengths of the two strings do not matter. Merely find the first differing pair of characters, and base the result on them.

Question 10:Decide on the following:ComparisonZero, Positive, or Negative"bugbear".compareTo("Bugbear")"rugrat".compareTo("rugRat")"ant".compareTo("turtle")"toadstool".compareTo("total")"ABCDEFG".compareTo("ABcD")"roadrunner".compareTo("roadkill")

## 11. All the Rules

Answer:"bugbear".compareTo("Bugbear")positive"rugrat".compareTo("rugRat")positive"ant".compareTo("turtle")negative"toadstool".compareTo("total")negative"ABCDEFG".compareTo("ABcD")negative"roadrunner".compareTo("roadkill")positive

# All the Rules

Here are all the rules for comparing strings:

Rule 1: If A.compareTo(B) == 0, then A and B are the same length (counting all characters, including blanks and punctuation) and each character in A is identical (including case) to the character in B at the same location.

Rule 2: Otherwise, if string A is a prefix of string B, then A.compareTo(B) < 0. If B is a prefix of string A, then A.compareTo(B) > 0.

Rule 3: Otherwise, find the first differing pair of characters in the strings A and B. Call them Achar and Bchar. Then A.compareTo(B) is negative if Achar comes before Bchar in the alphabet used by Java (and otherwise is positive).

The rules about what character comes first in the alphabet depend on what country you are in. This is one of the aspects of internationalization, which is the subject of customizing programs for use in different countries. Lets not worry about that.

Question 11:Of course, you would like to practice this:ComparisonWhich Rule?Zero, Negative, or Positive"turtle".compareTo("turtledove")"polarbear".compareTo("polarbear")"freezing point".compareTo("freezing")"Power".compareTo("power")"FORTRAN".compareTo("fortran")

## 12. Collating Sequence

Answer:"turtle".compareTo("turtledove")negative"polarbear".compareTo("polarbear")zero"freezing point".compareTo("freezing")positive"Power".compareTo("power")negative"FORTRAN".compareTo("fortran")negative

# Collating Sequence

The alphabet that Java uses in comparing characters is called a collating sequence. All characters are placed into this sequence, so any two characters can be compared. Here is the part of the sequence that includes the most common characters:

sp ! " # \$ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?@  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _  a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~

Characters are listed in increasing value, so

A < K0 < ZZ < a% < + @ < {z < ~

The first character listed 'sp' stands for the single space character. For example,

" hello".compareTo("hello")

returns a negative value.

Most of the time you don't need these details. But sometimes you do, so it is nice to know that they exist. The fact that space comes before nearly all other characters is sometimes useful to explain unexpected program behavior.

Question 12:More practice. Compare digit-containing strings like "23.5" using character-by-character string comparison, not arithmetic comparison.ComparisonZero, Negative, or Positive" 9999".compareTo("023")"(rat)".compareTo("[cat]")"23.5".compareTo("23,7")"More Cheese?".compareTo("More Cheese!")"cobol".compareTo("cobalt")

## 13. Ordered Array

Answer:ComparisonZero, Negative, or Positive" 9999".compareTo("023")negative"(rat)".compareTo("[cat]")negative"23.5".compareTo("23,7")positive"More Cheese?".compareTo("More Cheese!")positive"cobol".compareTo("cobalt")positive

# Ordered Array The elements of an ordered array are arranged in ascending (or descending) order. In general, an ordered array can have duplicate elements. (In some situations, though, an array is guaranteed not to have duplicates.) The picture shows an array of ints arranged into ascending order.

The elements of an array can be arranged in order by using a static sort() method of the Arrays class.

// Sort the array into ascending orderstatic void sort( array )

There are sort() methods for arrays of type byte[] , char[] , double[] , float[] , int[], and long[]. There is also a method that can sort object references based on the values of the objects.

Sorting is an important process in computer programming. Many data processing operations depend on data that is sorted, much as the data in a filing cabinet is kept sorted.

Question 13:Would a dictionary be useful if its definitions were not in sorted order?

## 14. Integer Sorting Program

Answer:No

# Integer Sorting Program Here is a program that uses the static void sort( int[] ) method of Arrays. The method is static so it can be used without constructing an Arrays object.

import java.util.Arrays;

class ArrayDemoOne
{
public static void main ( String[] args )
{
int[] scramble = {148, -23, 67, 110, -17, 44, 103, -12, -8, 91, -12, 43, 0, 9, 80, 34, 21, 44, 15, 11};

System.out.print("Scrambled array:  ");
for ( int j=0; j < scramble.length; j++ )
System.out.print( scramble[j] + " ");

System.out.println();

Arrays.sort( scramble );

System.out.print("Sorted    array:  ");
for ( int j=0; j < scramble.length; j++ )
System.out.print( scramble[j] + " ");

System.out.println();

}
}

The output of the program is:

Scrambled array:  148 -23 67 110 -17 44 103 -12 -8 91 -12 43 0 9 80 34 21 44 15 11Sorted    array:  -23 -17 -12 -12 -8 0 9 11 15 21 34 43 44 44 67 80 91 103 110 148

Question 14:Could compareTo() be used to decide on the order for an array of String references?

## 15. Integer Sorting Program

Answer:Yes.

# Integer Sorting Program Here is a picture of an ordered array. Each cell of the array holds a reference to a String. The order of the Strings is determined by the values returned by the compareTo() method for Strings.

For any two strings X and Y, if X.compareTo(Y) is negative, then X is left of Y in the ordered array.

For an array of object references, the sort() method automatically uses the compareTo() method of the class of objects being sorted. The class must implement the Comparable interface (and so must have a compareTo() method).

static void sort( Object[] a )
// Sorts the array a into ascending order,// as determined by the values compareTo() returns.// Each cell of the array must refer to an object// (must not be null).

If not all cells of the array are filled, use

static void sort( Object[] a,                   int fromIndex, int toIndex )   // Sorts the array a into ascending order,// as determined by the values compareTo() returns.//// Only the cells between the two indexes are sorted.// Each of those cells  must refer to an object.

Question 15:Does String implement Comparable?

## 16. String Sorting Program

Answer:Yes. So an array of String references can be sorted.

# String Sorting Program

Here is a program that demonstrates how sort() is used with an array of String references.

Notice the use of the for-each loops.

The output of the program is:

Scrambled array:  bat fox gnu eel ant dog fox gnatSorted    array:  ant bat dog eel fox fox gnat gnu

import java.util.Arrays;

class ArrayDemoTwo
{
public static void main ( String[] args )
{
String[] animals = {"bat", "fox", "gnu", "eel", "ant", "dog", "fox", "gnat" };

System.out.print("Scrambled array:  ");
for ( String anm : animals )
System.out.print( anm + " ");

System.out.println();

Arrays.sort( animals );

System.out.print("Sorted    array:  ");
for ( String anm : animals )
System.out.print( anm + " ");

System.out.println();

}
}

Question 16:To use sort() with a class that you define, what interface must that class implement?

## 17. Dictionary Entry

Answer:The class must implement Comparable.

# Dictionary Entry

Say that you are writing a program that acts like a dictionary. A dictionary entry has two instance variables: the word that it defines and the definition.

A class that implements Comparable<T> must implement the method int compareTo( T other ) where T is the type of the class.

Since our Entry implements the Comparable<Entry> interface, it must implement the method int compareTo( Entry other ).

class Entry implements Comparable<Entry>
{
private String word;
private String definition;

public Entry ( String word, String definition )
{
this.word = word;
this.definition = definition;
}

public String getWord()
{
return word;
}

public String getDefinition()
{
return definition;
}

public String toString()
{
return getWord() + "\t" + getDefinition();
}

public int compareTo( Entry other )
{
return  ;
}

}

Question 17:When the entries of a dictionary are put in order, does the order depend on the definition?Should the compareTo() method depend on the definition?Fill in the blank to complete the compareTo() method.Hint: use the compareTo() method of the String.

## 18. Entry Testing Program

Answer:When the entries of a dictionary are put in order, does the order depend on the definition? No.Should the compareTo() method depend on the definition? No.Fill in the blank to complete the compareTo() method.  public int compareTo( Entry other )
{
return getWord().compareTo( other.getWord() );
}
Another solution is:  public int compareTo( Entry other )
{
return word.compareTo( other.word );
}


# Entry Testing Program

Here is a program that tests that the Entry class works as expected.

import java.util.Arrays;

class Entry implements Comparable<Entry>
{
.  .  .
}

class EntryTester
{

public static void main ( String[] args )
{
Entry[] wordList = new Entry;

wordList = new Entry( "WWW", "World Wide Web" );
wordList = new Entry( "HTTP","Hypertext Transport Protocol" );
wordList = new Entry( "DNS", "Domain Name System" );
wordList = new Entry( "AWT", "Application Windowing Toolkit" );
wordList = new Entry( "CPU", "Central Processing Unit" );
wordList = new Entry( "RAM", "Random Access Memory" );
wordList = new Entry( "URL", "Uniform Resource Locator" );
wordList = new Entry( "GUI", "Graphical User Interface" );
wordList = new Entry( "API", "Application Programming Interface" );
wordList = new Entry( "ROM", "Read-only Memory" );

Arrays.sort( wordList );

for ( int j=0; j<wordList.length; j++ )
System.out.println( wordList[j].toString() );
}

}

The program outputs:

API     Application Programming InterfaceAWT     Application Windowing ToolkitDNS     Domain Name SystemCPU     Central Processing UnitGUI     Graphical User InterfaceROM     Read-only MemoryHTTP    Hypertext Transport ProtocolRAM     Random Access MemoryURL     Uniform Resource LocatorWWW     World Wide Web

The sort() method used our compareTo() to determine the order of the entries.

Question 18:Must an array be in sorted order for it to be searched?

## 19. Binary Search

Answer:No. Linear search can be used to look through the entries one-by-one starting with the first entry.


# Binary Search

Linear search is slow. Just think of using it by hand with a paper dictionary. Looking up "zebra" would take a long time if you first had to inspect every entry that preceded it. Usually you search for an entry by guessing about where it will be in the dictionary and then going to that page. If your guess is correct, you are done. Otherwise you refine your guess by looking at the page you picked and deciding if your new guess should go forward or backward. You can do this because the words are in sorted order.

When an array is ordered, an algorithm called binary search can be used to search for an entry. This algorithm works about the same way as you do when you search a dictionary. The Arrays class has several binarySearch() methods that can quickly search arrays of primitive types or of object references.

Let us look at the one that searches an array of object references.

static int binarySearch( Object[] array, Object key )

Search the array for an object that matches key, using the compareTo() method. If the object is found, return the index of the object in the array. Otherwise, return a negative value.

Details (safe to skip, for now): If the return value R is negative, then (-R) is one cell beyond where the key would be found if it were in the array. Use this value to insert a new element into its proper place in the array. (Move elements at (-R) and above to make room.)

If (-R) equals the size of the array, then the key is not in the array, and it should go at the very end, but there is no room.

For now, let us use binary search for searching and not insert new entries into the array.

Question 19:With a dictionary of just 10 entries, does it make much difference how fast searching is?


## 20. Tiny Dictionary

Answer:No... but you should know that binary search exists in case you need it in a large application. With large amounts of data, binary search is very much faster than linear search.


# Tiny Dictionary

import java.util.Arrays;
import java.util.Scanner;

class TinyDictionary
{

public static void main ( String[] args )
{
Entry[] wordList = new Entry;

wordList = new Entry( "WWW", "World Wide Web" );
wordList = new Entry( "HTTP","Hypertext Transport Protocol" );
wordList = new Entry( "DNS", "Domain Name System" );
wordList = new Entry( "AWT", "Application Windowing Toolkit" );
wordList = new Entry( "CPU", "Central Processing Unit" );
wordList = new Entry( "RAM", "Random Access Memory" );
wordList = new Entry( "URL", "Uniform Resource Locator" );
wordList = new Entry( "GUI", "Graphical User Interface" );
wordList = new Entry( "API", "Application Programming Interface" );
wordList = new Entry( "ROM", "Read-only Memory" );

Arrays.sort( wordList );

Scanner scan = new Scanner( System.in );
String key = "";
int location;

System.out.print("Word: ");
key = scan.next();

while ( !key.equals("quit") && !key.equals("q") )
{
location = Arrays.binarySearch( wordList, new Entry( key, "" ) );

if ( location < 0 )
System.out.println("Not in the dictionary");
else
System.out.println( wordList[location]  );

System.out.print("Word: ");
key = scan.next();
}

}

}           

The following program implements a tiny dictionary. The user enters a word, the program looks up the word and prints the word and its definition. With a little work, this program could be turned into an almost practical application.

The binary search method is a static method of the Arrays class, so it can be invoked by Arrays.binarySearch() without the need for an Arrays object.

The parameters are a sorted list of Entry objects, and an Entry object to serve as the key to look up. The key is constructed using the word the user entered and an empty string for the definition:

new Entry( key, "" )

Since the compareTo() method does not look at the definition, this works fine.

Here is sample output from the program:

Word: URLURL     Uniform Resource LocatorWord: WWWWWW     World Wide WebWord: quit

Question 20:Must all the cells of the array be non-null to use Arrays.binarySearch()?


## 21. Monster Object

Answer:Yes.

# Monster Object

Say that you are writing a computer game that involves a hero who encounters various monsters. Monsters have several characteristics: hit pointsstrengthage, and name. The number of hit points a monster has is how far it is from death. A monster with a large number of hit points is hard to kill. The hero also has hit points.

When the hit points of the hero reach zero, the game is over. The strength of a monster affects how many hit points the hero looses when the monster hits the hero. The age and name of the monster do not affect the outcome of battles between the monster and a hero.

Monster needs a compareTo() method so that monsters can be compared. For example, the game will present the hero with monsters in increasing order of difficulty.

Here is an outline of the Monster class.

class Monster implements
{
private int hitPoints, strength, age;
private String name;

public Monster( int hp, int str, int age, String nm )
{
hitPoints = hp; strength = str; this.age = age; name = nm;
}

public int getHitPoints() { return hitPoints; }

public int getStrength()  { return strength; }

public int getAge() { return age; }

public String getName() { return name; }

public String toString()
{
return "HP: " + getHitPoints() + " \tStr: " + getStrength() + "\t" + getName();
}

public int compareTo(  )
{

.... more goes here ...
}
}

Question 21:Fill in the blanks.


## 22. Use only some Instance Variables

Answer:See Below

# Use only some Instance Variables

The compareTo() method takes a reference to another Monster as a parameter.


class Monster implements Comparable<Monster>
{

. . .

public int compareTo( Monster other )
{

.... more goes here ...
}
}

Typically, only some of the instance variables of a complex object are used by compareTo(). Say that you want monsters to be listed in ascending order of hit points. Monsters with the same number of hit points are ordered by ascending strength.

It is easy to get this backwards. What you want is for compareTo(Monster other) to return a negative int when the monster that owns the method is less than the other monster.

Here is a partially completed method that does that:

 public int compareTo( Monster other )
{
int hitDifference = getHitPoints()-other.getHitPoints();

if (  )
return hitDifference;

else
return  ;

}

Question 22:Fill in the blanks.


## 23. End of Chapter

Answer:

public int compareTo( Monster other )
{
int hitDifference = getHitPoints()-other.getHitPoints();

if ( hitDifference != 0 )
return hitDifference;
else
return getStrength()-other.getStrength();

}

`

# End of Chapter

You have reached the end of the chapter. You may wish to search this list for something that interests you.