泛型和Object
package com.enterprise.article.base.generic;
public class TestGeneric2<T> {
public <T> T test(T t) {
return t;
}
public static void main(String[] args) {
TestGeneric2 objectTestGeneric2 = new TestGeneric2();
TestGeneric2<String> stringTestGeneric2 = new TestGeneric2<>();
// 需要强制转化成
Object test = objectTestGeneric2.test(new String());
// 不需要强制转化
String test1 = stringTestGeneric2.test(new String());
}
}
由此可见,使用泛型,有2个好处:
1.不需要做强制类型转换
2.编译时更安全。如果使用Object类的话,你没法保证返回的类型一定是String,也许是其它类型。这时你就会在运行时得到一个类型转换异常(ClassCastException)