0 0

转型为参数化类编译器无警告<泛型相关>5

在做 <Java编程思想>(4th)的15.4.5的代码的时候碰到一个问题:

   代码如下

 

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 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(); // 这里的代码不会有警告
		System.out.println(tt);
		System.out.println(tt2);
	}
}

 

public class TwoTuple<A,B> {
	private final A 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;
	}
}

 f2()方法返回的是无参数化的TwoTuple对象

我现在将它转型为带参数的,编译器不会有任何提醒,而且会代码正常运行

如果换用f() 或者 TwoTuple 的构造器  会报错 

这是为什么?

 

 


问题补充:使用new ByteArrayOutputStream()是故意测试的
这段代码没有实际意义
2014年4月21日 15:06
目前还没有答案

相关推荐

Global site tag (gtag.js) - Google Analytics