Results 1 to 2 of 2

Thread: Use of ternary

  1. #1
    wulfgarpro is offline Member
    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    Default Use of ternary

    Hi,

    Java Code:
    public int indexOf(E e) {
        for (ListIterator<E> it = listIterator(); it.hasNext(); )
            if (e == null ? it.next() == null : e.equals(it.next()))
                return it.previousIndex();
        return -1;  // Element not found
    }
    Can someone explain how this ternary expression works ? Why is there also an if ?

    wulfgarpro.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,422
    Rep Power
    20

    Default

    Always use braces of if/else/while/do...while blocks even when not strictly necessary and you'll have less problems understanding the code.

    The if is not part of the ternary, it's just a very common construct
    Java Code:
    if (trueOrFalseIsTrue) {
      // do something
    }
    The value of the boolean checked by the if statement is the value of the ternary, which is:
    if e is null, it.next() == null // note that this evaluates to true or false
    otherwse, e.equals(it.next()) // note that this also evaluates to true or false

    db

Similar Threads

  1. Replies: 2
    Last Post: 02-27-2010, 08:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •