Comparable Interface
Objects that have an ordering are compared using the compareTo() method.
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.