Java基础之泛型下限的体现

小鱼儿 2022-12-10 08:39 230阅读 0赞
  1. package cn.itcast.p5.generic.advance.demo;
  2. import java.util.Comparator;
  3. import java.util.Iterator;
  4. import java.util.TreeSet;
  5. import cn.itcast.p2.bean.Person;
  6. import cn.itcast.p2.bean.Student;
  7. import cn.itcast.p2.bean.Worker;
  8. public class GenericAdvanceDemo4 {
  9. /**
  10. * @param args
  11. */
  12. public static void main(String[] args) {
  13. TreeSet<Person> al1 = new TreeSet<Person>(new CompByName());
  14. al1.add(new Person("abc4",34));
  15. al1.add(new Person("abc1",30));
  16. al1.add(new Person("abc2",38));
  17. TreeSet<Student> al2 = new TreeSet<Student>(new CompByName());
  18. al2.add(new Student("stu1",11));
  19. al2.add(new Student("stu7",20));
  20. al2.add(new Student("stu2",22));
  21. TreeSet<Worker> al3 = new TreeSet<Worker>();
  22. al3.add(new Worker("stu1",11));
  23. al3.add(new Worker("stu2",22));
  24. TreeSet<String> al4 = new TreeSet<String>();
  25. al4.add("abcdeef");
  26. // al1.addAll(al4);//错误,类型不匹配。
  27. // al1.addAll(al2);
  28. // al1.addAll(al3);
  29. // System.out.println(al1.size());
  30. Iterator<Student> it = al2.iterator();
  31. while(it.hasNext()){
  32. System.out.println(it.next());
  33. }
  34. }
  35. }
  36. /*
  37. * class TreeSet<Worker>
  38. * {
  39. * Tree(Comparator<? super Worker> comp);
  40. * }
  41. *
  42. * 什么时候用下限呢?通常对集合中的元素进行取出操作时,可以是用下限。
  43. *
  44. */
  45. class CompByName implements Comparator<Person>{
  46. @Override
  47. public int compare(Person o1, Person o2) {
  48. int temp = o1.getName().compareTo(o2.getName());
  49. return temp==0? o1.getAge()-o2.getAge():temp;
  50. }
  51. }
  52. class CompByStuName implements Comparator<Student>{
  53. @Override
  54. public int compare(Student o1, Student o2) {
  55. int temp = o1.getName().compareTo(o2.getName());
  56. return temp==0? o1.getAge()-o2.getAge():temp;
  57. }
  58. }
  59. class CompByWorkerName implements Comparator<Worker>{
  60. @Override
  61. public int compare(Worker o1, Worker o2) {
  62. int temp = o1.getName().compareTo(o2.getName());
  63. return temp==0? o1.getAge()-o2.getAge():temp;
  64. }
  65. }

在这里插入图片描述

发表评论

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

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

相关阅读

    相关 java下限

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