码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 47、泛型


    一、引入

    1、传统方法:

    1. package generic_;
    2. import java.util.ArrayList;
    3. @SuppressWarnings({"all"})
    4. public class Generic01 {
    5. public static void main(String[] args) {
    6. ArrayList arrayList=new ArrayList();
    7. arrayList.add(new Dog("旺财",10));
    8. arrayList.add(new Dog("发财",1));
    9. arrayList.add(new Dog("招财",5));
    10. for(Object o:arrayList){
    11. Dog dog=(Dog)o;//向下转型
    12. System.out.println(dog.getName()+"-"+dog.getAge());
    13. }
    14. //旺财-10
    15. //发财-1
    16. //招财-5
    17. //如果不小心加入了一只猫,没有报错
    18. arrayList.add(new Cat("加菲猫",8));
    19. }
    20. }
    21. class Dog{
    22. private String name;
    23. private int age;
    24. public Dog(String name,int age){
    25. this.name=name;
    26. this.age=age;
    27. }
    28. public String getName() {
    29. return name;
    30. }
    31. public void setName(String name) {
    32. this.name = name;
    33. }
    34. public int getAge() {
    35. return age;
    36. }
    37. public void setAge(int age) {
    38. this.age = age;
    39. }
    40. }
    41. class Cat{
    42. private String name;
    43. private int age;
    44. public Cat(String name, int age) {
    45. this.name = name;
    46. this.age = age;
    47. }
    48. public String getName() {
    49. return name;
    50. }
    51. public void setName(String name) {
    52. this.name = name;
    53. }
    54. public int getAge() {
    55. return age;
    56. }
    57. public void setAge(int age) {
    58. this.age = age;
    59. }
    60. }

     2、使用泛型:

    1. package generic_;
    2. import java.util.ArrayList;
    3. @SuppressWarnings({"all"})
    4. public class Generic01 {
    5. public static void main(String[] args) {
    6. //解读:
    7. //1、ArrayList表示存放到ArrayList集合中的元素是Dog类型
    8. //2、如果编译器发现添加的类型,不满足要求,就会报错
    9. //3、在遍历时,可以直接取出Dog类型,而不是Object
    10. ArrayList arrayList=new ArrayList();
    11. arrayList.add(new Dog("旺财",10));
    12. arrayList.add(new Dog("发财",1));
    13. arrayList.add(new Dog("招财",5));
    14. arrayList.add(new Cat("加菲猫",8));//报错
    15. for(Dog dog:arrayList){
    16. System.out.println(dog.getName()+"-"+dog.getAge());
    17. }
    18. //旺财-10
    19. //发财-1
    20. //招财-5
    21. }
    22. }
    23. class Dog{
    24. private String name;
    25. private int age;
    26. public Dog(String name,int age){
    27. this.name=name;
    28. this.age=age;
    29. }
    30. public String getName() {
    31. return name;
    32. }
    33. public void setName(String name) {
    34. this.name = name;
    35. }
    36. public int getAge() {
    37. return age;
    38. }
    39. public void setAge(int age) {
    40. this.age = age;
    41. }
    42. }
    43. class Cat{
    44. private String name;
    45. private int age;
    46. public Cat(String name, int age) {
    47. this.name = name;
    48. this.age = age;
    49. }
    50. public String getName() {
    51. return name;
    52. }
    53. public void setName(String name) {
    54. this.name = name;
    55. }
    56. public int getAge() {
    57. return age;
    58. }
    59. public void setAge(int age) {
    60. this.age = age;
    61. }
    62. }

    3、 使用传统方法的问题分析:
    (1)不能对加入到集合ArrayList中的数据类型进行约束(不安全)
    (2)遍历的时候,需要进行类型转换,如果集合中的数据量较大,对效率有影响

    4、泛型的好处
    (1)编译时,检查添加元素的类型,提高了安全性
    (2)减少了类型转换的次数,提高效率
     ·不使用泛型
    Dog ->加入->object->取出->Dog//放入到Arraylist会先转成Object,在取出时,还需要转换成Dog
    ·使用泛型
    Dog->Dog->Dog//放入时和取出时,不需要类型转换,提高效率
    (3)不再提示编译警告

    二、基本介绍:(“泛”:a whole group of things, not specific)
    1、老韩理解:泛型=>Integer,String,Dog,可以表示数据类型的一种类型
    (1)泛型又称参数化类型,是Jdk5.0出现的新特性,解决数据类型的安全性问题
    (2)在类声明或实例化时只要指定好需要的具体的类型即可
    (3)Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生ClassCastException异常。同时,代码更加简洁、健壮
    (4)泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,或者是某个方法的返回值的类型,或者是参数类型。

    1. package generic_;
    2. public class Generic02 {
    3. public static void main(String[] args) {
    4. Person person=new Person("韩顺平教育");
    5. person.t();//class java.lang.String
    6. //此时class Person{}里面的所有的E都用String替换
    7. Person person1=new Person(1);
    8. person1.t();//class java.lang.Integer
    9. //此时class Person{}里面的所有的E都用Integer替换
    10. }
    11. }
    12. class Person{
    13. E s;//E表示s的数据类型,该数据类型在定义Person对象时指定,即在编译期间,就确定E是什么类型
    14. public Person(E s) {//E也可以参数类型
    15. this.s = s;
    16. }
    17. public E f(){//返回类型使用E
    18. return s;
    19. }
    20. public void t(){
    21. System.out.println(s.getClass());//显示s的运行类型
    22. }
    23. }

    2、泛型的语法:

    (1)泛型的声明:
    interface接口和class类
     //比如:List,ArrayList
    说明:
    1)其中,T,K,V不代表值,而是表示类型
    2)任意字母都可以。常用T表示,是Type的缩写
    (2)泛型的实例化:
    要在类名后面指定类型参数的值(类型)。如:
    1)List strList= new ArrayList0;

    2) Iterator iterator = customers.iterator0;

    (3)

     //我的代码:

    1. package generic_;
    2. import java.util.*;
    3. @SuppressWarnings({"all"})
    4. public class TestGeneric2 {
    5. public static void main(String[] args) {
    6. Student student=new Student();
    7. Student student1=new Student();
    8. Student student2=new Student();
    9. HashSet hashSet=new HashSet();
    10. hashSet.add(student);
    11. hashSet.add(student1);
    12. hashSet.add(student2);
    13. HashMap hashMap = new HashMap();
    14. hashMap.put("jack",student);
    15. hashMap.put("tom",student1);
    16. hashMap.put("smith",student2);
    17. System.out.println("====================");
    18. Set keyset=hashMap.keySet();
    19. for (Object key :keyset) {
    20. System.out.println(key+"-"+hashMap.get(key));
    21. }
    22. System.out.println("====================");
    23. Set entrySet=hashMap.entrySet();
    24. for (Object entry:entrySet) {
    25. Map.Entry m=(Map.Entry)entry;
    26. System.out.println(m.getKey()+"-"+m.getValue());
    27. }
    28. }
    29. }
    30. class Student{
    31. E student;
    32. }
    33. //====================
    34. //tom-generic_.Student@4f3f5b24
    35. //smith-generic_.Student@15aeb7ab
    36. //jack-generic_.Student@27d6c5e0
    37. //====================
    38. //tom-generic_.Student@4f3f5b24
    39. //smith-generic_.Student@15aeb7ab
    40. //jack-generic_.Student@27d6c5e0

    //老师的代码:

    1. package generic_;
    2. import java.util.*;
    3. @SuppressWarnings({"all"})
    4. public class TestGeneric2 {
    5. public static void main(String[] args) {
    6. HashSet students=new HashSet();
    7. students.add(new Student("jack",18));
    8. students.add(new Student("tom",28));
    9. students.add(new Student("mary",19));
    10. for (Student student :students) {
    11. System.out.println(student);
    12. }
    13. HashMap hm = new HashMap();
    14. hm.put("tom",new Student("tom",28));
    15. hm.put("smith",new Student("smith",48));
    16. hm.put("hsp",new Student("hsp",28));
    17. //迭代器
    18. /*自动填充的原因(hm.entrySet().var):
    19. public Set> entrySet(){
    20. Set> es;
    21. return (es=entrySet)==null?(entrySet=new EntrySet()):es;
    22. }
    23. */
    24. Set> entries = hm.entrySet();
    25. /*自动填充的原因(entries.iterator().var):
    26. public final Iterator> iterator(){
    27. return new EntryIterator();
    28. }
    29. */
    30. Iterator> iterator = entries.iterator();
    31. System.out.println("===========================");
    32. while (iterator.hasNext()) {
    33. Map.Entry next=iterator.next();
    34. System.out.println(next.getKey()+"-"+next.getValue());
    35. }
    36. }
    37. }
    38. //Student{name='mary', age=19}
    39. //Student{name='jack', age=18}
    40. //Student{name='tom', age=28}
    41. //===========================
    42. //tom-Student{name='tom', age=28}
    43. //smith-Student{name='smith', age=48}
    44. //hsp-Student{name='hsp', age=28}
    45. class Student{
    46. private String name;
    47. private int age;
    48. public Student(String name, int age) {
    49. this.name = name;
    50. this.age = age;
    51. }
    52. public String getName() {
    53. return name;
    54. }
    55. public void setName(String name) {
    56. this.name = name;
    57. }
    58. public int getAge() {
    59. return age;
    60. }
    61. public void setAge(int age) {
    62. this.age = age;
    63. }
    64. @Override
    65. public String toString() {
    66. return "Student{" +
    67. "name='" + name + '\'' +
    68. ", age=" + age +
    69. '}';
    70. }
    71. }

    3、泛型使用的注意事项和细节:
    (1)interface List{},public class HashSet{}.等等
    说明:T,E只能是引用类型,不能是基本数据类型
    看看下面语句是否正确?:
    List list = new ArrayList();//对
    List list2 = new ArrayList();//错

    (2)在指定泛型具体类型后,可以传入该类型或者其子类类型
    (3)泛型使用形式
    List list1 = new Arraylist();
    List list2 = new ArrayList<>()://推荐,因为编译器会自动进行类型推断
    (4)如果我们这样写List  list3=new  ArrayList();默认给它的泛型是[E就是Object]

    4、课堂练习题

     //我的代码:

    1. package generic_;
    2. import java.util.ArrayList;
    3. import java.util.Comparator;
    4. @SuppressWarnings({"all"})
    5. public class GenericExercise01 {
    6. public static void main(String[] args) {
    7. ArrayList arrayList=new ArrayList();
    8. Employee jack = new Employee("jack", 10000, new MyDate(2000, 1, 1));
    9. Employee tom = new Employee("tom", 20000, new MyDate(2001, 1, 1));
    10. Employee smith = new Employee("smith", 30000, new MyDate(2002, 1, 1));
    11. arrayList.add(jack);
    12. arrayList.add(tom);
    13. arrayList.add(smith);
    14. arrayList.sort(new Comparator() {
    15. @Override
    16. public int compare(Employee o1, Employee o2) {
    17. if(o1.getName().equals(o2.getName())){
    18. if(o1.getBirthday()==o2.getBirthday()){
    19. }else if(o1.getBirthday().getYear()==o2.getBirthday().getYear()){
    20. if(o1.getBirthday().getMonth()==o2.getBirthday().getMonth()){
    21. if(o1.getBirthday().getDay()==o2.getBirthday().getDay()){
    22. return 0;
    23. }else{
    24. return o1.getBirthday().getDay()-o2.getBirthday().getDay();
    25. }
    26. }else{
    27. return o1.getBirthday().getMonth()-o2.getBirthday().getMonth();
    28. }
    29. }else{
    30. return o1.getBirthday().getYear()-o1.getBirthday().getYear();
    31. }
    32. }else{
    33. return o1.getName().length()-o2.getName().length();
    34. }
    35. return 0;
    36. }
    37. });
    38. System.out.println(arrayList);
    39. //[Employee{name='tom', sal=20000.0, birthday=MyDate{year=2001, month=1, day=1}}, Employee{name='jack', sal=10000.0, birthday=MyDate{year=2000, month=1, day=1}}, Employee{name='smith', sal=30000.0, birthday=MyDate{year=2002, month=1, day=1}}]
    40. }
    41. }
    42. class Employee{
    43. private String name;
    44. private double sal;
    45. private MyDate birthday;
    46. public Employee(String name, double sal, MyDate birthday) {
    47. this.name = name;
    48. this.sal = sal;
    49. this.birthday = birthday;
    50. }
    51. public String getName() {
    52. return name;
    53. }
    54. public void setName(String name) {
    55. this.name = name;
    56. }
    57. public double getSal() {
    58. return sal;
    59. }
    60. public void setSal(double sal) {
    61. this.sal = sal;
    62. }
    63. public MyDate getBirthday() {
    64. return birthday;
    65. }
    66. public void setBirthday(MyDate birthday) {
    67. this.birthday = birthday;
    68. }
    69. @Override
    70. public String toString() {
    71. return "Employee{" +
    72. "name='" + name + '\'' +
    73. ", sal=" + sal +
    74. ", birthday=" + birthday +
    75. '}';
    76. }
    77. }
    78. class MyDate{
    79. private int year;
    80. private int month;
    81. private int day;
    82. public MyDate(int year, int month, int day) {
    83. this.year = year;
    84. this.month = month;
    85. this.day = day;
    86. }
    87. public int getYear() {
    88. return year;
    89. }
    90. public void setYear(int year) {
    91. this.year = year;
    92. }
    93. public int getMonth() {
    94. return month;
    95. }
    96. public void setMonth(int month) {
    97. this.month = month;
    98. }
    99. public int getDay() {
    100. return day;
    101. }
    102. public void setDay(int day) {
    103. this.day = day;
    104. }
    105. @Override
    106. public String toString() {
    107. return "MyDate{" +
    108. "year=" + year +
    109. ", month=" + month +
    110. ", day=" + day +
    111. '}';
    112. }
    113. }

    //老师的代码:

    1. package generic_;
    2. import java.util.ArrayList;
    3. import java.util.Comparator;
    4. @SuppressWarnings({"all"})
    5. public class GenericExercise01 {
    6. public static void main(String[] args) {
    7. ArrayList employees=new ArrayList();
    8. employees.add(new Employee("jack", 10000, new MyDate(2000, 1, 1)));
    9. employees.add(new Employee("tom", 20000, new MyDate(2001, 1, 1)));
    10. employees.add(new Employee("smith", 30000, new MyDate(2002, 1, 1)));
    11. System.out.println("employees="+employees);
    12. employees.sort(new Comparator() {
    13. @Override
    14. public int compare(Employee o1, Employee o2) {
    15. //验证传入的参数
    16. if(!(o1 instanceof Employee&&o2 instanceof Employee)){
    17. System.out.println("类型不正确");
    18. return 0;
    19. }
    20. //比较name
    21. int i=o1.getName().compareTo(o2.getName());
    22. if (i != 0) {
    23. return i;
    24. }
    25. return o1.getBirthday().compareTo(o2.getBirthday());
    26. }
    27. });
    28. System.out.println("=========排序后=========");
    29. System.out.println("employees="+employees);
    30. }
    31. }
    32. //employees=[
    33. //Employee{name='jack', sal=10000.0, birthday=MyDate{year=2000, month=1, day=1}},
    34. //Employee{name='tom', sal=20000.0, birthday=MyDate{year=2001, month=1, day=1}},
    35. //Employee{name='smith', sal=30000.0, birthday=MyDate{year=2002, month=1, day=1}}]
    36. //=========排序后=========
    37. //employees=[
    38. //Employee{name='jack', sal=10000.0, birthday=MyDate{year=2000, month=1, day=1}},
    39. //Employee{name='smith', sal=30000.0, birthday=MyDate{year=2002, month=1, day=1}},
    40. //Employee{name='tom', sal=20000.0, birthday=MyDate{year=2001, month=1, day=1}}]
    41. class Employee{
    42. private String name;
    43. private double sal;
    44. private MyDate birthday;
    45. public Employee(String name, double sal, MyDate birthday) {
    46. this.name = name;
    47. this.sal = sal;
    48. this.birthday = birthday;
    49. }
    50. public String getName() {
    51. return name;
    52. }
    53. public void setName(String name) {
    54. this.name = name;
    55. }
    56. public double getSal() {
    57. return sal;
    58. }
    59. public void setSal(double sal) {
    60. this.sal = sal;
    61. }
    62. public MyDate getBirthday() {
    63. return birthday;
    64. }
    65. public void setBirthday(MyDate birthday) {
    66. this.birthday = birthday;
    67. }
    68. @Override
    69. public String toString() {
    70. return '\n'+"Employee{" +
    71. "name='" + name + '\'' +
    72. ", sal=" + sal +
    73. ", birthday=" + birthday +
    74. '}';
    75. }
    76. }
    77. class MyDate{
    78. private int year;
    79. private int month;
    80. private int day;
    81. public MyDate(int year, int month, int day) {
    82. this.year = year;
    83. this.month = month;
    84. this.day = day;
    85. }
    86. public int getYear() {
    87. return year;
    88. }
    89. public void setYear(int year) {
    90. this.year = year;
    91. }
    92. public int getMonth() {
    93. return month;
    94. }
    95. public void setMonth(int month) {
    96. this.month = month;
    97. }
    98. public int getDay() {
    99. return day;
    100. }
    101. public void setDay(int day) {
    102. this.day = day;
    103. }
    104. @Override
    105. public String toString() {
    106. return "MyDate{" +
    107. "year=" + year +
    108. ", month=" + month +
    109. ", day=" + day +
    110. '}';
    111. }
    112. //把对year-month-day的比较封装到MyDate类里面
    113. public int compareTo(MyDate o){
    114. //比较birthday的year
    115. int yearMinus=year-o.getYear();
    116. if (yearMinus != 0) {
    117. return yearMinus;
    118. }
    119. //比较birthday的month
    120. int monthMinus=month-o.getMonth();
    121. if (monthMinus != 0) {
    122. return monthMinus;
    123. }
    124. //比较birthday的day
    125. return day-o.getDay();
    126. }
    127. }

    5、自定义泛型(1)基本语法:

    1. class类名{//可以有多个泛型
    2.  成员
    3. }

    (2)注意细节:
    1)普通成员可以使用泛型(属性、方法)
    2)使用泛型的数组,不能初始化
    3)静态方法中不能使用类的泛型
    4)泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)

    5)如果在创建对象时,没有指定类型,默认为Object

    1. package generic_;
    2. import java.util.ArrayList;
    3. @SuppressWarnings({"all"})
    4. public class CustomMethodGeneric {
    5. public static void main(String[] args) {
    6. Car car = new Car();
    7. car.fly("宝马",100);//当调用方法时,传入参数,编译器就会确定类型
    8. //class java.lang.String
    9. //class java.lang.Integer
    10. System.out.println("========================");
    11. car.fly(300,100.1);//当调用方法时,传入参数,编译器就会确定类型
    12. //class java.lang.Integer
    13. //class java.lang.Double
    14. System.out.println("========================");
    15. Fish fish = new Fish<>();
    16. fish.hello(new ArrayList(),11.3f);
    17. //class java.util.ArrayList
    18. //class java.lang.Float
    19. }
    20. }
    21. class Car{//普通类
    22. public void run(){
    23. }
    24. //1、就是泛型
    25. //2、是提供给fly使用的,不是返回类型
    26. public void fly(T t,R r){//泛型方法
    27. System.out.println(t.getClass());//自动装箱,String / Integer / Double...
    28. System.out.println(r.getClass());//自动装箱,String / Integer / Double...
    29. }
    30. }
    31. class Fish{//泛型类
    32. public void run(){
    33. }
    34. public void eat(U u,M m){//泛型方法
    35. }
    36. //1、hi()方法不是泛型方法
    37. //2、是hi()方法使用了类声明的泛型
    38. //3、泛型方法 和 方法使用泛型 是不一样的
    39. public void hi(T t){
    40. }
    41. //泛型方法,可以使用类声明的泛型,也可以使用自己声明泛型
    42. public void hello(R r,K k){//(R r,K k)中的R来自类的声明处,K来自方法的定义处
    43. System.out.println(r.getClass());
    44. System.out.println(k.getClass());
    45. }
    46. }

    6、泛型的继承和通配符:
    (1)泛型不具备继承性
    List list= new  ArrayList()://对吗?
    (2)<?>:支持任意泛型类型
    (3)<?extends A>:支持A类以及A类的子类,规定了泛型的上限
    (4)<?super A>:支持A类以及A类的父类,不限于直接父类,规定了泛型的下限

    1. package generic_;
    2. import java.util.ArrayList;
    3. import java.util.List;
    4. public class GenericExtends {
    5. public static void main(String[] args) {
    6. List list1=new ArrayList<>();
    7. List list2=new ArrayList<>();
    8. List list3=new ArrayList<>();
    9. List list4=new ArrayList<>();
    10. List list5=new ArrayList<>();
    11. //List
    12. printCollection1(list1);
    13. printCollection1(list2);
    14. printCollection1(list3);
    15. printCollection1(list4);
    16. printCollection1(list5);
    17. //List
    18. printCollection2(list1);//报错
    19. printCollection2(list2);//报错
    20. printCollection2(list3);
    21. printCollection2(list4);
    22. printCollection2(list5);
    23. //List
    24. printCollection3(list1);
    25. printCollection3(list2);//报错
    26. printCollection3(list3);
    27. printCollection3(list4);//报错
    28. printCollection3(list5);//报错
    29. }
    30. //方法一:
    31. //List表示任意的泛型类型都可以接受
    32. public static void printCollection1(List c){
    33. for(Object object:c){//通配符,取出时,就是Object
    34. System.out.println(object);
    35. }
    36. }
    37. //方法二:
    38. //:规定了泛型的上限,可以接受A或A子类
    39. public static void printCollection2(List c){
    40. for(Object object:c){
    41. System.out.println(object);
    42. }
    43. }
    44. //方法三:
    45. //子类类名A:支持A类以及A类的父类,不限于直接父类,规定了泛型的下限
    46. public static void printCollection3(Listsuper A> c){
    47. for(Object object:c){
    48. System.out.println(object);
    49. }
    50. }
    51. }
    52. class A{
    53. }
    54. class B extends A{
    55. }
    56. class C extends B{
    57. }
    58. 7、

       //我的代码:

      1. package generic_;
      2. import java.util.List;
      3. import java.util.Map;
      4. import java.util.Set;
      5. @SuppressWarnings({"all"})
      6. public class Homework01 {
      7. public static void main(String[] args) {
      8. User jack = new User(1, 18, "jack");
      9. User tom = new User(2, 19, "tom");
      10. User smith = new User(3, 20, "smith");
      11. }
      12. }
      13. class DAO{
      14. Map stu;
      15. public DAO(Map stu) {
      16. this.stu = stu;
      17. }
      18. public void save(String id, T entity){
      19. System.out.println(stu.put(id,entity));
      20. }
      21. public T get(String id){
      22. return stu.get(id);
      23. }
      24. public void update(String id,T entity){
      25. System.out.println(stu.replace(id,entity));
      26. }
      27. public List list(){
      28. Set keySet=stu.keySet();
      29. List list=null;
      30. int size=stu.size();
      31. for(int i=0;i
      32. list.add(stu.get(keySet));
      33. }
      34. return list;
      35. }
      36. public void delete(String id){
      37. System.out.println(stu.remove(id));
      38. }
      39. }
      40. class User{
      41. private int id;
      42. private int age;
      43. private String name;
      44. public User(int id, int age, String name) {
      45. this.id = id;
      46. this.age = age;
      47. this.name = name;
      48. }
      49. public int getId() {
      50. return id;
      51. }
      52. public void setId(int id) {
      53. this.id = id;
      54. }
      55. public int getAge() {
      56. return age;
      57. }
      58. public void setAge(int age) {
      59. this.age = age;
      60. }
      61. public String getName() {
      62. return name;
      63. }
      64. public void setName(String name) {
      65. this.name = name;
      66. }
      67. @Override
      68. public String toString() {
      69. return "User{" +
      70. "id=" + id +
      71. ", age=" + age +
      72. ", name='" + name + '\'' +
      73. '}';
      74. }
      75. }

      //老师的代码:

      1. package generic_;
      2. import innerclass.D;
      3. import org.junit.Test;
      4. import java.util.List;
      5. import java.util.Map;
      6. import java.util.Set;
      7. @SuppressWarnings({"all"})
      8. public class Homework01 {
      9. public static void main(String[] args) {
      10. User jack = new User(1, 18, "jack");
      11. User tom = new User(2, 19, "tom");
      12. User smith = new User(3, 20, "smith");
      13. }
      14. @Test
      15. public void testList(){
      16. DAO dao=new DAO<>();
      17. dao.save("001",new User(1,10,"jack"));
      18. dao.save("002",new User(2,18,"king"));
      19. dao.save("003",new User(3,38,"smith"));
      20. List list=dao.list();
      21. System.out.println("list="+list);
      22. System.out.println("==============================");
      23. dao.update("003",new User(3,58,"milan"));
      24. dao.delete("001");
      25. list=dao.list();
      26. System.out.println("list="+list);
      27. System.out.println("==============================");
      28. System.out.println("id==003:"+dao.get("003"));
      29. }
      30. }
      31. //list=[User{id=1, age=10, name='jack'}, User{id=2, age=18, name='king'}, User{id=3, age=38, name='smith'}]
      32. //==============================
      33. //list=[User{id=2, age=18, name='king'}, User{id=3, age=58, name='milan'}]
      34. //==============================
      35. //id==003 User{id=3, age=58, name='milan'}
      1. package generic_;
      2. import java.util.*;
      3. public class DAO{
      4. private Map map=new HashMap<>();//搞清楚怎么定义这个成员变量的
      5. public void save(String id, T entity){
      6. map.put(id,entity);
      7. }
      8. public T get(String id){
      9. return map.get(id);
      10. }
      11. public void update(String id,T entity){
      12. map.put(id,entity);
      13. }
      14. //遍历map[k-v],将map的所有value(T entity),封装到ArrayList返回即可
      15. public List list(){
      16. List list = new ArrayList<>();
      17. Set keySet=map.keySet();
      18. for (String key:keySet) {
      19. list.add(map.get(key));
      20. }
      21. return list;
      22. }
      23. public void delete(String id){
      24. map.remove(id);
      25. }
      26. }
      1. package generic_;
      2. public class User{
      3. private int id;
      4. private int age;
      5. private String name;
      6. public User(int id, int age, String name) {
      7. this.id = id;
      8. this.age = age;
      9. this.name = name;
      10. }
      11. public int getId() {
      12. return id;
      13. }
      14. public void setId(int id) {
      15. this.id = id;
      16. }
      17. public int getAge() {
      18. return age;
      19. }
      20. public void setAge(int age) {
      21. this.age = age;
      22. }
      23. public String getName() {
      24. return name;
      25. }
      26. public void setName(String name) {
      27. this.name = name;
      28. }
      29. @Override
      30. public String toString() {
      31. return "User{" +
      32. "id=" + id +
      33. ", age=" + age +
      34. ", name='" + name + '\'' +
      35. '}';
      36. }
      37. }

      三、JUnit

      1、为什么需要JUnit?

      (1) 一个类有很多功能代码需要测试,为了测试,就需要写入到main方法中
      (2) 如果有多个功能代码测试,就需要来回注销,切换很麻烦
      (3)如果可以直接运行一个方法,就方便很多,并且可以给出相关信息,就好了

      2、基本介绍:
      (1)JUnit是一个Java语言的单元测试框架
      (2)多数Java的开发环境都已经集成了JUnit作为单元测试的工具

      3、操作:

      (1)在要测试的方法上面写“@Test”

       2、快捷键alt+enter,“Add 'JUnit5.4' to classpath”,选最新的就行了

       3、下次用时就可以自动导入了,点击“小绿箭”就可以运行了

       

    59. 相关阅读:
      使用推测解码 (Speculative Decoding) 使 Whisper 实现 2 倍的推理加速
      pycharm终端pip安装模块成功但还是显示找不到 ModuleNotFoundError: No module named
      JavaWeb-CSS
      HTML5期末大作业:基于HTML+CSS+JavaScript校园文化企业网站模板【学生网页设计作业源码】
      环境配置 | 有关NLP的库安装学习使用示例,原理解释及出错解析
      Edexcel A-Level化学真题讲解(5)
      Spring Boot + vue-element 开发个人博客项目实战教程(二十五、项目完善及扩展(前端部分))
      性能调优,看过的都说会了...
      AI识万物:从0搭建和部署手语识别系统 ⛵
      JAVA学习(4)-全网最详细~
    60. 原文地址:https://blog.csdn.net/weixin_72052233/article/details/128054489
      • 最新文章
      • 攻防演习之三天拿下官网站群
        数据安全治理学习——前期安全规划和安全管理体系建设
        企业安全 | 企业内一次钓鱼演练准备过程
        内网渗透测试 | Kerberos协议及其部分攻击手法
        0day的产生 | 不懂代码的"代码审计"
        安装scrcpy-client模块av模块异常,环境问题解决方案
        leetcode hot100【LeetCode 279. 完全平方数】java实现
        OpenWrt下安装Mosquitto
        AnatoMask论文汇总
        【AI日记】24.11.01 LangChain、openai api和github copilot
      • 热门文章
      • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
        奉劝各位学弟学妹们,该打造你的技术影响力了!
        五年了,我在 CSDN 的两个一百万。
        Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
        面试官都震惊,你这网络基础可以啊!
        你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
        心情不好的时候,用 Python 画棵樱花树送给自己吧
        通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
        13 万字 C 语言从入门到精通保姆级教程2021 年版
        10行代码集2000张美女图,Python爬虫120例,再上征途
      Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
      正则表达式工具 cron表达式工具 密码生成工具

      京公网安备 11010502049817号