泛型的了解

本文深入探讨了Java中的泛型,包括泛型类、泛型接口、类型通配符、上限与下限的设定、泛型方法以及通配符的下限。通过示例展示了泛型在保证数据安全性方面的应用,同时讲解了如何使用和限制通配符来增强代码的灵活性和兼容性。
摘要由CSDN通过智能技术生成

泛型

作用:为了保证数据类型的安全性。
示例:
public class Point<T> {
    private T x;
    private T y;

    public Point(){}
    public Point(T x, T y) {
        this.x = x;
        this.y = y;
    }
}
public class Location<E,T> {
    private E x;
    private T y;

    public Location(){}
    public Location(E x, T y) {
        this.x = x;
        this.y = y;
    }
}

泛型的菱形语法

Point<String> p3 = new Point<>();
Point<Float>  p5 = new Point<>(67.4f,48.3f);
Location<Float,Integer> lo1 = new Location<>();

一、定义泛型接口与类

public class Point<T> {}
public class ArrayList<E>{}

public interface A<E>{}
public interface B<E,T>{}
public interface List<E> {}
public interface Map<K,V>{}

二、类型通配符

 // ? 通配符,可以匹配任何类型
    public static  void test(Point<?> p){

    }

    public static void main(String[] args) {
        Point<String> p1 =   new Point<>();
        test(p1);

        Point<Float> p2 =   new Point<>();
        test(p2);
    }

三、设置类型通配符的上限

 public static  void test(Point<? extends Account> p){ // 形参

 }

//调用
public static void main(String[] args) {
 	Point<SavingAccount> p1 =   new Point<>();
	Point<CreditAccount> p2 =   new Point<>();
	test(p1);
	test(p2);
}

四、设置泛型的上限

public class Point< T extends Number>{  //类
    
}

五、泛型方法

public class Point {
   //泛型方法 :泛型定义在方法级别上,作用域就是该方法
    public static <E> void test(Point<E> p){
        
    }
}

六、泛型与通配符


    public void test(Point<? extends E>){

    }
}

//测试
Point<Account> p = new Point<>();
test(p) ;// ? 通配符 只能是Accout的子类
 

public boolean addAll(Collection<? extends E> c) { }

七、通配符的下限

public class Point<E> {
    public void test(Point<? super E>){

    }
}


//测试
//E 若是Account , ? 通配符只能是Account , Object

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值