CSC152 2005S, Class 14: Conditionals, Continued
Admin:
* Cool talk Thursday in "convo slot". Extra credit for attending.
* Syllabus revamped; project eliminated
* Apologies for wasting time
Overview:
* Questions on yesterday?
* About writing equals and compareTo methods.
* Lab, continued.
/Questions on yesterday?/
* No
/Standard comparison methods/
* Recall: Good practice to write a "toString" method for every class. Why?
* Java's default way of printing objects is, well, confusing.
* It is often useful to access things in string form.
* Some constructors expect strings. For example, new BigInteger(...);
* It looks normal when you print it out.
* Why not tostr or twostring or makethisintoanicestringpleaseorimayhavetocry?
* Good name
* Convention <---
* Why convention?
* Java takes advantage of it. When you use an object in string context, it calls the toString method.
* Other programmers know about it.
* Java has a wide variety of "standard" methods
* Two relevant to today:
* equals(Object o)
* compareTo(Object o)
* equals compares "this" to o to determine if they are equal
* The definition of equality depends on the kind of thing you're talking about
* For example, two fractions are equal if their reduced forms are the same
* Lazier programmers might say that the two fractions are equal only if they have the same nuemrator and denominator
* compareTo compares "this" to o and returns
* negative number, if this "is naturally smaller than" o
* 0, if the two are naturally equal
* positive number, if this "is naturally larger than" o
* Why "a negative number" rather than a particular negative number?
* To make life easier for the programmer. For example, here's a good way to write compareTo for Integers
return this.intValue() - other.intValue();
* typical use:
Is foo less than bar? if (foo.compareTo(bar) < 0)
Is foo equal to bar? if (foo.compareTo(bar) == 0)
Is foo greater than bar? if (foo.compareTo(bar) > 0)
* Hidden problem: The parameter is an Object, not the type you want
* To determine the type of something, use instanceof operator
if (value instanceof Type)
/**
* Determine if this fraction equals other.
*/
public boolean equals(Object other)
{
if (other instanceof Fraction) {
Fraction otherfraction = (Fraction) other;
return this.numerator.equals(otherfraction.numerator)
&& this.denominator.equals(otherfraction.denominator);
}
else if (((other instanceof Integer)
|| (other instanceof BigInteger))
&& (this.denominator.equals(BigInteger.valueOf(1)))) {
return this.numerator.equals(other);
}
else {
return false;
}
} // equals(Object)