Friday, December 2, 2011

Java's character and assorted string classes support text-processing - 2


Character supplies three methods that compare Character objects for ordering or other purposes. The public int compareTo(Character anotherCharacter) method compares the contents of two Characters by subtracting anotherCharacter's value field from the current Character's value field. The integer result returns. If the result is zero, both objects are the same (based on the value field only). If the result is negative, the current Character's value is numerically less than the anotherCharacter-referenced Character's value. Finally, a positive result implies that the current Character's value field is numerically greater than anotherCharacter's value field. A second overloaded public int compareTo(Object o) method works the same as compareTo(Character anotherCharacter) (and returns the same result), but compares the current Character and the o-referenced object (which must be of type Character, or the method throws a ClassCastException object). compareTo(Object o) allows Java's Collections Framework to sort Characters according to natural order. (A future article will discuss that method, sorting, and natural order.) Finally, the public final boolean equals(Object o) method compares the contents of the value field in the current Character with the contents of the value field in o. A Boolean true value returns if o is of type Character and if both value fields contain the same contents. Otherwise, false returns. To see the compareTo(Character anotherCharacter) and equals(Object o) methods in action, examine the following code fragment:
 
Character c1 = new Character ('A');
Character c2 = new Character ('B');
Character c3 = new Character ('A');
System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2));
System.out.println ("c1.equals (c2): " + c1.equals (c2));
System.out.println ("c1.equals (c3): " + c1.equals (c3));

System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2)); outputs -1 because A is (numerically) less than B. System.out.println ("c1.equals (c2): " + c1.equals (c2)); outputs false because the Characters that c1 and c2 reference contain different characters (A and B). Finally, System.out.println ("c1.equals (c3): " + c1.equals (c3)); outputs true because, although c1 and c3 reference different Characters, both objects contain the same character (A).

No comments: