so che è vecchio post, ma guarda caso molto simile e poi mi votare: P
Rispondendo alla domanda originale: un solo operando viene valutato MA:
@Test
public void test()
{
Integer A = null;
Integer B = null;
Integer chosenInteger = A != null ? A.intValue() : B;
}
@Test
public void test()
{
Integer A = null;
Integer B = null;
Integer chosenInteger = A != null ? A.intValue() : B;
}
Questo test genererà NullPointerException
sempre e in questo caso IF statemat non equivale a?: Operator.
Il motivo è qui http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.25. La parte sulla boxe/unboxing è coinvolto, ma può essere facilmente comprensibile guardando:
"If one of the second and third operands is of type boolean
and the type of the other is of type Boolean
, then the type of the conditional expression is boolean
."
Lo stesso vale per Integer.intValue()
i migliori saluti!
fonte
2013-02-26 06:44:09
È anche qualcosa di abbastanza semplice da poter provare e vedere cosa succede :) –
Che fornisce informazioni su una particolare istanza. Meglio trovare quello che dice lo standard. –