MEC@JavaSE@基础篇@笔记13@泛型初步

一、泛型

1、简介

泛型是java1.5版本之后提供的一种强大机制,它使得编程变得更加灵活,更加安全。

2、引入泛型的原因

案例:实现一个数组功能的逆序操作。

如果不用泛型,实例代码如下:

package com.mec.study;

public class AboutGeneric {

    public static int[] revArray(int[] m) {
        int temp;

        for (int i = 0; i < m.length/2; i++) {
            temp = m[i];
            m[i] = m[i+1];
            m[i+1] = temp;
        }

        return m;
    }

    public static long[] revArray(long[] m) {
        long temp;

        for (int i = 0; i < m.length/2; i++) {
            temp = m[i];
            m[i] = m[i+1];
            m[i+1] = temp;
        }

        return m;
    }

}

上面程序只处理了两种基本数据类型:int和long,每一个数据类型都需要将这个方法进行一次重载,这样的实现方式很笨,而为了简化这个问题的代码实现方式,java提出了“泛型”的概念。

这一个概念的核心就是:

                      编译时不确定,运行时在确定!

使用泛型实现代码示例:

package com.mec.study;

public class AboutGeneric {
    
    public static <T> T[] revArray(T[] m) {
        T temp;

        for (int i = 0; i < m.length/2; i++) {
            temp = m[i];
            m[i] = m[i+1];
            m[i+1] = temp;
        }

        return m;
    }

}

泛型格式:

                       

在方法返回值类型前出现的<T>,说明这个方法用到泛型(static可有可无,我的这个方法中用的是静态方法,所以有static);在以后的代码中,T就是代表某种类型,而这个类型的具体情况,需要等到方法被调用时,再根据实参进行判定。

需要注意的是:泛型只能是类类型。

3、利用泛型,还可以定义泛型类:

package com.mec.study;

public class MyGeneric<T> {
    private T member;

    public MyGeneric() {
    }

    public MyGeneric(T member) {
        this.member = member;
    }

    public T getMember() {
        return member;
    }

    public void setMember(T member) {
        this.member = member;
    }
}

上述代码中:

public class MyGeneric<T>

类名称后面的<T>是“泛型标志”,此后在代码中可以用T作为类型。同样的,T类型的具体情况,也是程序运行的时候,根据具体情况而定的。

泛型也可以是多个:

package com.mec.study;

public class MyGeneric<T, K> {
    private T member;
    private K obj;
}

4、泛型类使用示例代码

泛型类内容:

public class TestFanxing<T> {
    
    T t;
    
    public void method(){
        System.out.println(t);
    }
}

使用方式:

public class Test {

    public static void main(String[] args) {
        TestFanxing tf1 = new TestFanxing();//不加限制

        tf1.t = 10;//传递int值,正确
        tf1.method();

        tf1.t = "1234354";//传递String值,正确
        tf1.method();

        TestFanxing<String> tf2 = new TestFanxing();//加限制类型

        //tf2.t = 10;//报错
        tf2.t = "455edfd";//只能传递String,正确
        tf2.method();
    }

}

————————————————————————————————————————————————————————————————————————————————————————
10
1234354
455edfd

Process finished with exit code 0

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值