泛型~~~

1.概念

Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。

常见形式有泛型类、泛型接口、泛型方法。

2.语法

T称为类型占位符,表示一种引用类型。

3.优点

提高代码的重用性。

防止类型转换异常,提高代码的安全性。

案例演示:创建泛型类。

public class MyGeneric<T> {
//使用泛型T
//1创建变量
T t;
//2泛型作为方法的参数
public void show(T t) {
System.out.println(t);
}
//3泛型作为方法的返回值
public T getT() {
return t;
}
}
​

案例演示:泛型方法。

public class MyGenericMethod {
//泛型方法
public <T> T show(T t) {
System.out.println("泛型方法"+t);
return t;
}
}

案例演示:泛型接口。

public interface MyInterface<T> {
String name="张三";
T server(T t);
}
​

测试类:

public class TestGeneric {
public static void main(String[] args) {
    //使用泛型类创建对象
    MyGeneric<String> myGeneric=new MyGeneric<String>();
    myGeneric.t="hello";
    myGeneric.show("大家好,加油");
    String string=myGeneric.getT();
    
    MyGeneric<Integer> myGeneric2=new MyGeneric<Integer>();
    myGeneric2.t=100;
    myGeneric2.show(200);
    Integer integer=myGeneric2.getT();
    //泛型接口
    MyInterfaceImpl impl=new MyInterfaceImpl();
    impl.server("xxxxxxx");
    MyInterfaceImpl2<Integer> impl2=new MyInterfaceImpl2<>();
    impl2.server(1000);
    //泛型方法
    MyGenericMethod myGenericMethod=new MyGenericMethod();
    myGenericMethod.show("中国加油");
    myGenericMethod.show(200);
    myGenericMethod.show(3.14);
}
}

4.泛型集合

参数化类型、类型安全的集合,强制集合元素的类型必须一致。

特点: 编译时即可检查,而非运行时抛出异常。

访问时,不必类型转换(拆箱)。

        不同泛型之间引用不能相互赋值,泛型不存在多态。

public class TestArrayList2 {
public static void main(String[] args) {
    
    ArrayList<String> arrayList=new ArrayList<String>();
    arrayList.add("xxx");
    arrayList.add("yyy");
    // arrayList.add(10);
    // arrayList.add(20);
    
    for (String string : arrayList) {
        System.out.println(string);
    }
    
    ArrayList<Student> arrayList2=new ArrayList<Student>();
    Student s1=new Student("火箭", 20);
    Student s2=new Student("飞机", 22);
    Student s3=new Student("坦克", 18);
    
    arrayList2.add(s1);
    arrayList2.add(s2);
    arrayList2.add(s3);
    
    Iterator<Student> it=arrayList2.iterator();
    
    while(it.hasNext()) {
        Student s=it.next();
        System.out.println(s.toString());
    }
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值