zoukankan      html  css  js  c++  java
  • [bxd学习java基本点]13泛型类,泛型方法,当定义二种类型的泛型方法时,用迭代器的方法

    15-08
    自定义的类中使用泛型,即为泛型类
    class Worker{

    }
    class Student{

    }
    class Tool{
    private Object obj;
    public void setObject(Object obj){
    this.obj=obj;
    }
    public Worker getObject(){
    return obj;
    }
    }
    //什么时间来定义泛型类呢?
    当类中要操作的引用数据类型不确定时
    早期,定义Object来完成扩展
    现在定义泛型来扩展
    泛型的出现,不要再强转啊
    把错误存在了编译时
    class Utils<QQ>{
    private QQ q;
    publi void setObject(QQ q){
    this.q=q;
    }
    public QQ getObject(){
    return q;
    }
    }
    class GenericDemo3{
    public static void main(String[] args){
    Tool t=new Tool();
    t.setObject(new Worker());
    t.getObject();


    Utils<Worker> u=new Utils<Worker>();


    }
    }
    15-09泛型方法
    class Demo<T>{
    public void show(T t){
    sop("show:"+t);
    }
    }
    //泛型类的定义的泛型,在整个类中有效,若此法使用,
    //那么泛型类的对象一定要操作
    class Demo{
    public<T> void show(T t){
    sop("show:"+t);
    }
    public <T> void print(Q q){
    sop("print:"+t);
    }
    }
    class GenericDemo{
    public static void main(String[] args){
    Demo<Integer> d=new Demo<Integer>();
    d.show(new Integer(4));
    d.show(9);
    d.show("fdfdffd");//失败了,若要操作字符串,只能重新定义
    Demo<String> b=new Demo<String>();
    b.show("dddd");
    b.show(5);//失败了。


    //__________________使用泛型方法
    Demo d=new Demo();
    d.show("dfdffd");
    d.show(new Integer(4));
    d.print("ffd");
    }
    }
    15-10静态方法泛型
    15-11接口上
    15-12泛型的高级使用
    class GenericDemo6{
    public static void main(String[] args){
    ArrayList<String> al=new ArrayList<String>();
    al.add("fdfd");
    ArrayList<Integer> all=new ArrayList<Integer>();
    all.add(4);
    all.add(7);
    all.add(1);


    }
    public static void print(ArrayList<String> al){
    Integer<String> it=al.iterator();
    while(it.hasnext()){
    sop(it.next());
    }
    }
    //此法,只能使用string, 不能用Integer.怎么办啊
    呢??请使用?占位符
    public static void print(ArrayList<?> al){
    Integer<?> it=al.iterator();
    while(it.hasnext()){
    sop(it.next());
    }
    }
    法二
    public static<T> void print(ArrayList<T> al){
    Integer<T> it=al.iterator();
    while(it.hasnext()){
    T t=it.next();//此得可以操作的。。。。。
    //sop(it.next().length());//此时?不能用
    sop(it.next());
    }
    }
    泛型限定,未听会
    ?通配符:也可理解为占位符
    泛型的限定
    ?extends E:可以接收E类型或子类型
    ? super E:可以接收E类型或E的父类型

  • 相关阅读:
    Hadoop学习笔记—12.MapReduce中的常见算法
    Hadoop学习笔记—11.MapReduce中的排序和分组
    Hadoop学习笔记—10.Shuffle过程那点事儿
    Hadoop学习笔记—9.Partitioner与自定义Partitioner
    Hadoop学习笔记—8.Combiner与自定义Combiner
    Hadoop学习笔记—7.计数器与自定义计数器
    Hadoop学习笔记—6.Hadoop Eclipse插件的使用
    Hadoop学习笔记—5.自定义类型处理手机上网日志
    Hadoop学习笔记—4.初识MapReduce
    Hadoop学习笔记—3.Hadoop RPC机制的使用
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3020052.html
Copyright © 2011-2022 走看看