Convert a raw TwoTuple to TwoTuple<A,B> in a wrong way but didn't get any warning(Java Generics) -
enviroment: java se 7,eclipse 4.2 there r codes :
code 1:
import java.io.bytearrayoutputstream; public class tuple { static twotuple<string, integer> f() { return tuple("hi", 47); } static twotuple f2(){ return tuple(new bytearrayoutputstream(), 47); } public static <a,b> twotuple<a,b> tuple(a ,b b) { return new twotuple<a, b>(a, b); } public static void main(string[] args) { twotuple<string, integer> tt = f(); twotuple<boolean, integer> tt2 = f2(); // there wrong system.out.println(tt); system.out.println(tt2); } }
code 2:
public class twotuple<a,b> { private final a ; private final b b ; public twotuple(a f , b s) { // todo auto-generated constructor stub a= f; b=s; } @override public string tostring() { // todo auto-generated method stub return "a : " +a+ " ; b : "+b; } }
i made mistake ( twotuple tt2 = f2() )purposely,
but codes can run , compiler didn't think mistake,why?
your compiler accepts without errors (but not without warnings) since f2()
method returning raw twotuple
, , performing unchecked conversion twotuple<boolean, integer>
.
if change f2()
method type-safe signature below, error:
static twotuple<bytearrayoutputstream, integer> f2() { return tuple(new bytearrayoutputstream(), 47); }
Comments
Post a Comment