Day17_泛型

泛型

  • Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。
  • 常见形式有泛型类、泛型接口、泛型方法。
  • 语法:
    • <T,...>T称为类型占位符,表示一种引用类型。
  • 好处:
    • (1)提高代码的重用性
    • (2)防止类型转换异常,提高代码的安全性
package com.oop.demo13;

/**
 * 泛型方法
 * 语法:<T>返回值类型
 *
 */
public class MyGenericMethod {
    //泛型方法
    public <T> T show(T t){
        System.out.println ("泛型方法"+t);
        return t;
    }
}
package com.oop.demo13;

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> myGeneric1=new MyGeneric<Integer> ();
        myGeneric1.t=100;
        myGeneric1.show (200);
        String s=myGeneric.getT ();
        //泛型接口
        MyInterfaceImpl impl=new MyInterfaceImpl ();
        impl.server ("ssss");

        MyInterfaceImpl2<Integer> impl2=new MyInterfaceImpl2<> ();
        impl2.server (1000);

        //泛型方法
        MyGenericMethod myGenericMethod=new MyGenericMethod ();
        myGenericMethod.show ("zhongguo");
        myGenericMethod.show (200);
        myGenericMethod.show (3.14);

    }
}

泛型集合

  • 概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。
  • 特点:
    • 编译时即可检查,而非运行时抛出异常。
    • 访问时,不必类型转换(拆箱)。
    • 不同泛型之间引用不能相互赋值,泛型不存在多态。
package com.oop.demo13;

import com.oop.Demo12.Student;

import java.util.ArrayList;
import java.util.Iterator;

public class Demo03 {
    public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList <String>();
        arrayList.add ("xxxxxxx");
        arrayList.add ("yyyyyyy");
        //arrayList.add (10);
        //arrayList.add (20);
        for (Object object : arrayList) {
            System.out.println (object);
        }

        ArrayList<Student> arrayList1=new ArrayList<Student> ();
        Student s1=new Student ("xiaoming",10);
        Student s2=new Student ("xiaoHong",16);
        Student s3=new Student ("xiaobai",14);
        arrayList1.add (s1);
        arrayList1.add (s2);
        arrayList1.add (s3);
        Iterator<Student> it =arrayList1.iterator ();
        while (it.hasNext ()){
            Student s=it.next ();
            System.out.println (s);
        }
    }
}
posted @ 2020-12-03 09:00  柠檬情  阅读(56)  评论(0编辑  收藏  举报