public class generictype {
public static void main(String str[]) {
Hashtable h =new Hashtable();
h.put(1, "String类型");
int a = (String) h.get(1);
System.out.println(a);
}
}
//执行结果
String类型
//如果我们将上述由红色标出的String改为int执行后结果如下(更改后编译没有错误):
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at genetictype.generictype.main(generic1.java:10)
public class generictype {
public static void main(String str[]) {
Hashtable<Integer, String> h = new Hashtable<Integer, String>();
h.put(1, "String类型");
String a= h.get(1);
System.out.println(a);
}
}
//执行结果
string类型
//需要提出的是1.上述由红色标出的String如果改为int,在编译的时候会报错
2.在h.get(1)前面不需要再进行强制类型转换。
public class generictype
{
public static void main(String str[]){
test1<String> t = new test1<String>();
test1<Date> tt = new test1<Date>();
System.out.println(t.a);
System.out.println(tt.a);
}
}
class test1<T>{
static int a = 1;
}
//结果
1
public class generictype {public static void main(String str[]) {
test3 t =new test3();
t.getT("11111");
}
}
interface test2<T>{
public T getT(T t);
}
class test3 implements test2<String>{
public String getT(String t){
return t;
}
}
//类型擦除后的代码
public class generictype {
public static void main(String str[]) {
test3 t = new test3();
t.getT("11111");
}
interface test2 {
public Object getT(Object t);
}
class test3 implements test2 {
public String getT(String T){
return T }
public Object getT(Object t) {
return this.getT((String) t);
}//如果没有这段代码,在类型擦除后test3没有重写接口test2的抽象方法,明显错误,因此编译器的巨大作用就是在这里帮忙生成了该方法,同时编译器也依靠该功能完成检错任务。
}
public class generictype {
public static void main(String str[]) {
test<Integer, String> t = new test<Integer, String>();
t.put(1, "str1");
t.put(2, "str2");
System.out.println(t.get(1));
System.out.println(t.get(2));
}
}
class test<T, V> {
public Hashtable<T, V> h = new Hashtable<T, V>();
public void put(T t, V v) {
h.put(t, v);
}
public V get(T t) {
return h.get(t);
}
}
//执行结果
str1
str2
public class generictype {
public <T> String getString(T obj){
return obj.toString();
}
public static void main(String str[]) {
generictype g =new generictype ();//不需要类的泛型
System.out.println(g.getString(1));
System.out.println(g.getString('a'));
System.out.println(g.getString("a"));
}
}
//执行结果
a
a
public class generictype {
public static void main(String str[]) {
TestException t =new TestException();
try {
t.excute(2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//extends说明该泛型参数继承于Exception
interface TestExceptionInterface<T extends Exception>
{
public void excute(int i) throws T;
}
class TestException implements TestExceptionInterface<IOException>{
@Override
public void excute(int i) throws IOException {
if(i<10){
throw new IOException();
}
}
}
//意义:1.针对不同的可能出现的异常类型,定义自己的实现类。
2.定义多个实现类的时候,不用一个一个手动throws异常,提高了代码重用率
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有