zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
    
  • 相关阅读:
    Java的HttpServletRequest
    Java的用户登录计数功能
    JAVA-DATE
    正则表达式
    Java-JDBC(2)
    Java-JDBC(1)
    String类
    java的多态和构造方法
    Java的封装 this关键字 继承
    java抽象类与接口
  • 原文地址:https://www.cnblogs.com/lemonlover/p/14077623.html
Copyright © 2011-2022 走看看