-1

Could someone give me a detailed explanation of what's going on here; I'm getting confused by the ?:

 for (int i = 0; i < datasize; i++) {
            String data1value = data1.size() > i ? data1.get(i) : null;
            String data2value = data2.size() > i ? data2.get(i) : null;
            String data3value = data3.size() > i ? data3.get(i) : null;
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bimal
  • 61
  • 1
  • 10

2 Answers2

1

The ternary operator is being used to prevent getting an IndexOutOfBoundsException here. If the size of the Collection is > than current index i, it assigns that value through get(i), otherwise it assigns null.

If you had assigned the values directly as

 String data1value = data1.get(i);

your code could break if the loop runs for more than the number of items in the Collection.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

The ? : operator in Java is an expression which returns one of two values.

In Java you might write

if (a > b) {
  max = a;
}
else {
  max = b;
}

Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:

max = (a > b) ? a : b;

They are used be the reason presented in the response from Ravi Thapliyal.