JAVA基础之泛型

Java基础之泛型

泛型提供了编译时类型安全监测机制,该机制允许程序员在编译时检测到非法的类型。

泛型方法

public class FxDemo {
    public static <E> void  print(E arr[]){
        for(E data: arr){
            System.out.println(data);
        }
    }
    public static void main(String[] args) {
        Integer []a = {1,2,3};
        Double []b = {4.0,5.0,6.0};
        String []c = {"7","8","9"};
        FxDemo.print(a);
        FxDemo.print(b);
        FxDemo.print(c);
    }
}

有界类型的参数

限制那些被允许传递到一个类型参数的类型种类范围。

要声明一个有界的类型参数,首先列出类型参数的名称,后跟extends关键字。

public static <T extends Comparable<T>> T compare(T x,T y,T z){
    T max = x;
    if(y.compareTo(max)>0){
        max = y;
    }
    if(z.compareTo(max)>0){
        max = z;
    }
    return max;
}

泛型类

package classs.fx;

public class FxDemo<T> {

    public static <E> void print(E arr[]){
        for(E data: arr){
            System.out.println(data);
        }
    }

    public T say(T str){
        return str;
    }

    public static <T extends Comparable<T>> T compare(T x,T y,T z){
        T max = x;
        if(y.compareTo(max)>0){
            max = y;
        }
        if(z.compareTo(max)>0){
            max = z;
        }
        return max;
    }

    public static void main(String[] args) {
        FxDemo<String> fxDemo = new FxDemo<>();
        Integer []a = {1,2,3};
        Double []b = {4.0,5.0,6.0};
        String []c = {"7","8","9"};
        FxDemo.print(a);
        FxDemo.print(b);
        FxDemo.print(c);
        System.out.println("==============");
        System.out.println(FxDemo.compare(5,3,7));
        System.out.println("==============");
        System.out.println(fxDemo.say("haha"));
    }
}

类型通配符

类型通配符一般是使用?代替具体的类型参数,例如list<?>在逻辑上代表list,list

public static <T extends Comparable<T>> T compare(T x,T y,T z){
    T max = x;
    if(y.compareTo(max)>0){
        max = y;
    }
    if(z.compareTo(max)>0){
        max = z;
    }
    return max;
}
public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值