1

Hey all I'm trying to understand a bit of code in the GWT showcase, and I'm not sure what the following code does. Can someone explain it, and more importantly, explain why the syntax works the way it does? I haven't seen anything like it and I don't know why/how it works. Thanks!

public int compareTo(ContactInfo o) {
  return (o == null || o.firstName == null) ? -1 : -o.firstName.compareTo(firstName);
}
john
  • 775
  • 3
  • 15
  • 31
  • 1
    This is the inline if statement: "?:". Just like an actual if-then-else, it has a condition, a true-value and a false-value. – abiessu Sep 05 '13 at 16:10

5 Answers5

7

It means: If the condition is true, return -1, otherwise return -o.firstName.compareTo(firstName);

Its a shortcut syntax for if-then-else.

After the ? is what to do if condition is true

After the : is what to do if the condition is false

Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
Big Al
  • 980
  • 1
  • 8
  • 20
  • 1
    "Its a shortcut syntax for if then else." It's actually more as it can go inline with parts of expressions. – nanofarad Sep 05 '13 at 16:09
  • `Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement ` - http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html – Habib Sep 05 '13 at 16:09
  • Thanks everyone, explained very well, got it! – john Sep 05 '13 at 16:17
0

if o or o.firstName is null then returns -1; otherwise returns negative value of o.firstName compared to firstName.

svobol13
  • 1,842
  • 3
  • 25
  • 40
0

I assume that it is the '?' and ':' that confuses you. It is simply a shorthand notation for an if statement like so: expression ? then-value : else-value

So in your case it could be written like

public int compareTo(ContactInfo o) {
  if (o == null || o.firstName == null)
  then return -1;
  else return -o.firstName.compareTo(firstName);
}

(And of course the else can (and should) be omitted)

ArniDat
  • 534
  • 5
  • 15
0

That is called the ternary operator.

boolean value = (condition) ? true : false;

This blog post explains what it is and how to use it well.

http://alvinalexander.com/java/edu/pj/pj010018

Ben Dale
  • 2,492
  • 1
  • 14
  • 14
0

This method is from Comparable interface, in this case specific to ContactInfo. The definition of ContactInfo should be something like this

public class ContactInfo  implements Comparable<ContactInfo >{
    ...
}

The sentence :

contact.compareTo(otherContact);

Must return -1 if contact is less than otherContact (if firstName of contact is alphabetical less than firstName of otherContact), 0 if contact is equals to otherContact, and and 1 if great than.

Omar Mainegra
  • 4,006
  • 22
  • 30