Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

using casting combined with the ternary operator

807603Nov 14 2007 — edited Nov 14 2007
Hi everyone.
I have the following code, which works without problem:
if (list.get(0) instanceof A) {
    something = ((A) list.get(0)).getSomething();
} else {
    something = ((B) list.get(0)).getSomething();
}
...but my eyes hurt when I see it: two identical lines save for the type casting. So I tried this:
something = ((list.get(0) instanceof A? (A) : (B)) list.get(0)).getSomething();
...and it doesn't work! It gives me the following errors:

something = ((list.get(0) instanceof A? *(A)* : (B)) list.get(0)).getSomething();
A cannot be resolved

something = ((list.get(0) instanceof A? (A) : *(B)* ) list.get(0)).getSomething();
B cannot be resolved

something = ((list.get(0) instanceof A? (A) : (B)) list.get(0)).getSomething();
Syntax error on token "list", delete this token

Is it impossible to use the ternary operator here? I tried several combinations of parenthesis, just in case, unsuccessfully.

Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 12 2007
Added on Nov 14 2007
33 comments
581 views