In Java (Android) I had some code which looked like this:
for (Tuple tuple : xRange) {
Tuple5<Integer, Integer, Double, Double, Double> t = (Tuple5<Integer, Integer, Double, Double, Double>)tuple;
...
}
Which can be a pain to write. By the way, Tuple5 derives from Tuple.
So I wrote this method:
@SuppressWarnings("unchecked")
public static final <U1, U2 extends U1> U2 cast(U1 inst) {
return (U2)inst;
}
Looks nasty, huh? But this then allowed me to rewrite the code like this:
for (Tuple tuple : xRange) {
Tuple5<Integer, Integer, Double, Double, Double> t = cast(tuple);
...
}
I'm compiling on Android using the AIDE compiler. I'm thinking it may not even compile on other systems.
My question is does this work on all compilers? Is it bad code? And, if it is, then why?
Thanks
I think it's bad because of type erasure, it's not an accident that you get a compiler warning (which you suppress).
Your method
looks somewhat like this after type erasure:
so this will not be type-safe, that cast effectively does nothing. You can read more about type erasure here.