java 泛型的上限与下限、泛型通配符、泛型上下限

心已赠人 2023-10-03 10:58 37阅读 0赞

java 泛型的上限与下限
设置泛型对象的上限使用extends,表示参数类型只能是该类型或该类型的子类:

声明对象:类名<? extends 类> 对象名

定义类:类名<泛型标签 extends 类>{}

设置泛型对象的下限使用super,表示参数类型只能是该类型或该类型的父类:

声明对象:类名<? super 类> 对象名称

定义类:类名<泛型标签 extends类>{}

public static void show(List<? extends Number> l){}

public static void show(List<? super String> l){}

泛型的上限

  1. public static void main(String[] args) {
  2. Person<Integer> p1 = new Person<>();
  3. p1.setVal(99);
  4. Person<Double> p2 = new Person<>();
  5. p2.setVal(3.14);
  6. Person<String> p3 = new Person<>();
  7. p3.setVal("007");
  8. show(p1);//√
  9. show(p2);//√
  10. show(p3);//×
  11. }
  12. public static void show(Person<? extends Number> p){//此处限定了Person的参数类型只能是Number或者是其子类,而String并不属于Number。
  13. System.out.println(p.getVal());
  14. }

泛型的下限

  1. public static void main(String[] args) {
  2. Person<Integer> p1 = new Person<>();
  3. p1.setVal(99);//Integer
  4. Person<Double> p2 = new Person<>();
  5. p2.setVal(3.14);//Double
  6. Person<String> p3 = new Person<>();
  7. p3.setVal("007");//String
  8. Person<Object> p4 = new Person<>();
  9. p4.setVal(new Object());//Object
  10. show(p1);//×
  11. show(p2);//×
  12. show(p3);//√
  13. show(p4);//√
  14. }
  15. public static void show(Person<? super String> p){
  16. System.out.println(p.getVal());
  17. }

很好的例子!

  1. package generic;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class GenericDemo3 {
  5. public static void main(String[] args) {
  6. //因为show方法是用List<?>通配符接收的,所以可以是任意类型!
  7. List<String> l1 = new ArrayList<>();//new ArrayList<String>()
  8. show(l1);
  9. List<Double> l2 = new ArrayList<>();
  10. show(l2);
  11. List<Number> l3 = new ArrayList<>();
  12. show(l3);
  13. List<Object> l4 = new ArrayList<>();
  14. show(l4);
  15. //使用up方法的话接收类型为Number或者其子类
  16. //up(l1);//错误,因为up方法接收类型为Number或者其子类,l1(String)不符合!
  17. up(l2);
  18. up(l3);
  19. //使用down方法的话接收类型为Number或者其父类
  20. //down(l2);error
  21. down(l3);
  22. down(l4);
  23. }
  24. public static void down(List<? super Number> l){
  25. for (Object object : l) {
  26. System.out.println(object);
  27. }
  28. }
  29. public static void up(List<? extends Number> l){
  30. for (Object object : l) {
  31. System.out.println(object);
  32. }
  33. }
  34. public static void show(List<?> l){
  35. for (Object object : l) {
  36. System.out.println(object);
  37. }
  38. }
  39. }

发表评论

表情:
评论列表 (有 0 条评论,37人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java下限

    前言:   java的泛型上下限不是很好理解,尤其像我这种菜鸡。反反复复看了好几遍了...,真是... 一、简单的继承体系 class Person{}