Java Syntax Question

Started by
2 comments, last by Instigator 11 years, 7 months ago
I've recently been trying to undertand ternary operators and found an example using java - here -


public class EmpComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
Person emp1 = (Person) obj1;
Person emp2 = (Person) obj2;
int nameComp = emp1.getFirstName().compareTo(emp2.getFirstName());
return ((nameComp == 0) ? emp1.getLastName().compareTo(
emp2.getLastName()) : nameComp);
}



I am feeling really sick right now because of 2 things in this example which I'm obviously missing

1. Why doesn't he just return the "nameComp" variable..
2. In the "true" part of the ternary value he does "emp1.getLastName().compareTo(emp2.getLastName())" why.. the value is already in nameComp.

Please explain

Thanks!
Advertisement
#1 and #2 have the same answer.
Firstly first names are compared, if they are equal it compares last names and returns result, otherwise just nameComp is returned (which is comparison of first names).
Here's a somewhat clearer version of this.


public class EmpComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
Person emp1 = (Person) obj1;
Person emp2 = (Person) obj2;
int firstNameComp = emp1.getFirstName().compareTo(emp2.getFirstName());
int lastNameComp = emp1.getLastName().compareTo(emp2.getLastName());
return (nameComp == 0) ? lastNameComp : firstNameComp;
}
Thanks guys.. got it.

This topic is closed to new replies.

Advertisement