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