201771010102 常惠琢《2018面向对象程序设计(Java)》第10周学习总结

实验十  泛型程序设计技术

实验时间 2018-11-1

1、实验目的与要求

(1) 理解泛型概念;

(2) 掌握泛型类的定义与使用;

(3) 掌握泛型方法的声明与使用;

(4) 掌握泛型接口的定义与实现;

(5)了解泛型程序设计,理解其用途。

2、实验内容和步骤

实验1: 导入第8章示例程序,测试程序并进行代码注释。

测试程序1:

l 编辑、调试、运行教材311、312页 代码,结合程序运行结果理解程序;

l 在泛型类定义及使用代码处添加注释;

l 掌握泛型类的定义及使用。 

 1 package pair1;
 2 
 3 /**
 4  * @version 1.00 2004-05-10
 5  * @author Cay Horstmann
 6  */
 7 public class Pair<T> //Pair引入一个类型变量T
 8 {
 9    //类定义中的类型变量指定方法的返回类型以及域和局部变量的类型
10    private T first;
11    private T second;
12 
13    public Pair() { first = null; second = null; }
14    public Pair(T first, T second) { this.first = first;  this.second = second; }
15 
16    public T getFirst() { return first; }
17    public T getSecond() { return second; }
18 
19    public void setFirst(T newValue) { first = newValue; }
20    public void setSecond(T newValue) { second = newValue; }
21 }
 1 package pair1;
 2 
 3 /**
 4  * @version 1.01 2012-01-26
 5  * @author Cay Horstmann
 6  */
 7 public class PairTest1
 8 {
 9    public static void main(String[] args)
10    {
11       String[] words = { "Mary", "had", "a", "little", "lamb" };
12       Pair<String> mm = ArrayAlg.minmax(words);//mm保存minmax对象的返回值
13       System.out.println("min = " + mm.getFirst());
14       System.out.println("max = " + mm.getSecond());
15    }
16 }
17 
18 class ArrayAlg
19 {
20    /**
21     * Gets the minimum and maximum of an array of strings.
22     * @param a an array of strings
23     * @return a pair with the min and max value, or null if a is null or empty
24     *///版权、参数声明
25    public static Pair<String> minmax(String[] a)//用具体的类型替换类型变量实例化泛型类型
26    {
27       if (a == null || a.length == 0) return null;
28       String min = a[0];
29       String max = a[0];
30       for (int i = 1; i < a.length; i++)//a.length指数组的属性值
31       {
32          if (min.compareTo(a[i]) > 0) min = a[i];//比较同时保存最大值和最小值
33          if (max.compareTo(a[i]) < 0) max = a[i];//compareTo方法可实现字符串比较
34       }
35       return new Pair<>(min, max);//返回Pair<>带参数的构造器
36    }
37 }

测试程序2:

l 编辑、调试运行教材315页 PairTest2,结合程序运行结果理解程序;

l 在泛型程序设计代码处添加相关注释;

l 掌握泛型方法、泛型变量限定的定义及用途。

 1 package pair2;
 2 
 3 /**
 4  * @version 1.00 2004-05-10
 5  * @author Cay Horstmann
 6  */
 7 public class Pair<T> //Pair引入一个类型变量T
 8 {
 9    //类定义中的类型变量指定方法的返回类型以及域和局部变量的类型
10    private T first;
11    private T second;
12 
13    public Pair() { first = null; second = null; }
14    public Pair(T first, T second) { this.first = first;  this.second = second; }
15 
16    public T getFirst() { return first; }
17    public T getSecond() { return second; }
18 
19    public void setFirst(T newValue) { first = newValue; }
20    public void setSecond(T newValue) { second = newValue; }
21 }
 1 package pair2;
 2 
 3 import java.time.*;
 4 
 5 /**
 6  * @version 1.02 2015-06-21
 7  * @author Cay Horstmann
 8  */
 9 public class PairTest2
10 {
11    public static void main(String[] args)
12    {
13       LocalDate[] birthdays = 
14          { 
15             LocalDate.of(1906, 12, 9), // G. Hopper
16             LocalDate.of(1815, 12, 10), // A. Lovelace
17             LocalDate.of(1903, 12, 3), // J. von Neumann
18             LocalDate.of(1910, 6, 22), // K. Zuse
19          };
20       Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);//mm保存minmax对象的返回值
21       System.out.println("min = " + mm.getFirst());
22       System.out.println("max = " + mm.getSecond());
23    }
24 }
25 
26 class ArrayAlg
27 {
28    /**
29       Gets the minimum and maximum of an array of objects of type T.
30       @param a an array of objects of type T
31       @return a pair with the min and max value, or null if a is 
32       null or empty
33    */
34    //将T限制为实现了Comparable接口的类。  定义泛型变量的上界(泛型方法)
35    public static <T extends Comparable> Pair<T> minmax(T[] a) 
36    {
37       if (a == null || a.length == 0) return null;
38       T min = a[0];
39       T max = a[0];
40       for (int i = 1; i < a.length; i++)
41       {
42          if (min.compareTo(a[i]) > 0) min = a[i];
43          if (max.compareTo(a[i]) < 0) max = a[i];
44       }
45       return new Pair<>(min, max);//返回Pair<>带参数的构造器
46    }
47 }

 

 

测试程序3:

l 用调试运行教材335页 PairTest3,结合程序运行结果理解程序;

l 了解通配符类型的定义及用途。

 1 package pair3;
 2 
 3 import java.time.*;
 4 
 5 public class Employee
 6 {  
 7    private String name;
 8    private double salary;
 9    private LocalDate hireDay;
10 
11    public Employee(String name, double salary, int year, int month, int day)
12    {
13       this.name = name;
14       this.salary = salary;
15       hireDay = LocalDate.of(year, month, day);
16    }
17 
18    public String getName()
19    {
20       return name;
21    }
22 
23    public double getSalary()
24    {  
25       return salary;
26    }
27 
28    public LocalDate getHireDay()
29    {  
30       return hireDay;
31    }
32 
33    public void raiseSalary(double byPercent)
34    {  
35       double raise = salary * byPercent / 100;
36       salary += raise;
37    }
38 }
 1 package pair3;
 2 
 3 import pair3.Employee;
 4 
 5 public class Manager extends Employee
 6 {  
 7    private double bonus;
 8 
 9    /**
10       @param name the employee's name
11       @param salary the salary
12       @param year the hire year
13       @param month the hire month
14       @param day the hire day
15    */
16    public Manager(String name, double salary, int year, int month, int day)
17    {  
18       super(name, salary, year, month, day);
19       bonus = 0;
20    }
21 
22    public double getSalary()
23    { 
24       double baseSalary = super.getSalary();
25       return baseSalary + bonus;
26    }
27 
28    public void setBonus(double b)
29    {  
30       bonus = b;
31    }
32 
33    public double getBonus()
34    {  
35       return bonus;
36    }
37 }
 1 package pair3;
 2 
 3 /**
 4  * @version 1.00 2004-05-10
 5  * @author Cay Horstmann
 6  */
 7 public class Pair<T> //Pair引入一个类型变量T
 8 {
 9    //类定义中的类型变量指定方法的返回类型以及域和局部变量的类型
10    private T first;
11    private T second;
12 
13    public Pair() { first = null; second = null; }
14    public Pair(T first, T second) { this.first = first;  this.second = second; }
15 
16    public T getFirst() { return first; }
17    public T getSecond() { return second; }
18 
19    public void setFirst(T newValue) { first = newValue; }
20    public void setSecond(T newValue) { second = newValue; }
21 }
 1 package pair3;
 2 
 3 /**
 4  * @version 1.01 2012-01-26
 5  * @author Cay Horstmann
 6  */
 7 public class PairTest3
 8 {
 9    public static void main(String[] args)
10    {
11       Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
12       Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
13       Pair<Manager> buddies = new Pair<>(ceo, cfo);      
14       printBuddies(buddies);
15 
16       ceo.setBonus(1000000);
17       cfo.setBonus(500000);
18       Manager[] managers = { ceo, cfo };
19 
20       Pair<Employee> result = new Pair<>();
21       minmaxBonus(managers, result);
22       System.out.println("first: " + result.getFirst().getName() 
23          + ", second: " + result.getSecond().getName());
24       maxminBonus(managers, result);
25       System.out.println("first: " + result.getFirst().getName() 
26          + ", second: " + result.getSecond().getName());
27    }
28 
29    //定义泛型变量的下界 。
30    public static void printBuddies(Pair<? extends Employee> p)
31    {
32       Employee first = p.getFirst();
33       Employee second = p.getSecond();
34       System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
35    }
36  
37    //定义泛型变量的下界 。
38    public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
39    {
40       if (a.length == 0) return;
41       Manager min = a[0];
42       Manager max = a[0];
43       for (int i = 1; i < a.length; i++)
44       {
45          if (min.getBonus() > a[i].getBonus()) min = a[i];
46          if (max.getBonus() < a[i].getBonus()) max = a[i];
47       }
48       result.setFirst(min);
49       result.setSecond(max);
50    }
51    
52    //定义泛型变量的下界 。     “?"为下限通配符。
53    public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
54    {
55       minmaxBonus(a, result);
56       PairAlg.swapHelper(result); //OK——swapHelper捕获通配符类型
57    }
58    // 无法写入公共静态<T super manager> ...
59 }
60 
61 class PairAlg
62 {
63    public static boolean hasNulls(Pair<?> p)
64    {
65       return p.getFirst() == null || p.getSecond() == null;
66    }
67 
68    public static void swap(Pair<?> p) { swapHelper(p); }
69 
70    public static <T> void swapHelper(Pair<T> p)
71    {
72       T t = p.getFirst();
73       p.setFirst(p.getSecond());
74       p.setSecond(t);
75    }
76 }

 

实验2:编程练习:

编程练习1:实验九编程题总结

l 实验九编程练习1总结(从程序总体结构说明、目前程序设计存在的困难与问题三个方面阐述)。

程序总体结构:主类PairTest1和Pair<T>类

 目前程序设计存在的困难与问题:

         偶尔会存在读文件时,文件路径不正确,无法找到文件的问题,还有会读文件,但是就是自己编写有问题,要不就得百度,要不就查书,检查问题的。

l 实验九编程练习2总结(从程序总体结构说明、目前程序设计存在的困难与问题三个方面阐述)。

程序总体结构:主类PairTest2和Pair<T>类:

目前程序设计存在的困难与问题:

读代码问题不大,但还是存在编写程序的问题,我会通过多加练习慢慢提高。

编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。

 1 import java.io.FileNotFoundException;
 2 import java.io.IOException;
 3 import java.io.PrintWriter;
 4 import java.util.Scanner;
 5 public class Fine {
 6 
 7     public static void main(String[] args) {
 8                 Scanner in = new Scanner(System.in);
 9                 Min min=new Min();
10                 PrintWriter out = null;
11                 try {
12                     out = new PrintWriter("test.txt");
13                     int sum = 0;
14                     for (int i = 1; i <=10; i++) {
15                         int a = (int) Math.round(Math.random() * 100);
16                         int b = (int) Math.round(Math.random() * 100);
17                         int menu = (int) Math.round(Math.random() * 3);
18                         switch (menu) {
19                         case 0:
20                             System.out.println(i+":"+a + "+" + b + "=");
21                             int c1 = in.nextInt();
22                             out.println(a + "+" + b + "=" + c1);
23                             if (c1 == (a + b)) {
24                                 sum += 10;
25                                 System.out.println("恭喜答案正确");
26                             } else {
27                                 System.out.println("抱歉,答案错误");
28                             }
29                             break;
30                         case 1:
31                             while (a < b) {
32                                 b = (int) Math.round(Math.random() * 100);
33                             }
34                             System.out.println(i+":"+a + "-" + b + "=");
35                             int c2 = in.nextInt();
36                             out.println(a + "-" + b + "=" + c2);
37                             if (c2 == (a - b)) {
38                                 sum += 10;
39                                 System.out.println("恭喜答案正确");
40                             } else {
41                                 System.out.println("抱歉,答案错误");
42                             }
43 
44                             break;
45                         case 2:
46                             System.out.println(i+":"+a + "*" + b + "=");
47                             int c3 = in.nextInt();
48                             out.println(a + "*" + b + "=" + c3);
49                             if (c3 == a * b) {
50                                 sum += 10;
51                                 System.out.println("恭喜答案正确");
52                             } else {
53                                 System.out.println("抱歉,答案错误");
54                             }
55 
56                             break;
57                         case 3:
58                              while(b == 0){
59                                     b = (int) Math.round(Math.random() * 100);
60                                 }
61                                 while(a % b != 0){
62                                     a = (int) Math.round(Math.random() * 100);
63                                     
64                                 }
65                             System.out.println(i+":"+a + "/" + b + "=");
66                             int c4 = in.nextInt();
67                             if (c4 == a / b) {
68                                 sum += 10;
69                                 System.out.println("恭喜,答案正确");
70                             } else {
71                                 System.out.println("抱歉,答案错误");
72                             }
73 
74                             break;
75                         }
76                     }
77                     System.out.println("你的得分为" + sum);
78                     out.println("你的得分为" + sum);
79                     out.close();
80                 } catch (FileNotFoundException e) {
81                     e.printStackTrace();
82                 }
83             }
84         }
 1 public class Min<T> {
 2     private T a;
 3     private T b;
 4     public Min() {
 5         a=null;
 6         b=null;
 7     }
 8     public Min(T a,T b) {
 9         this.a=a;
10         this.b=b;
11     }
12     public int count1(int a,int b) {
13         return a+b;
14     }
15     public int count2(int a,int b) {
16         return a-b;
17     }
18     public int count3(int a,int b) {
19         return a*b;
20     }
21     public int count4(int a,int b) {
22         return a/b;
23     }
24 }

猜你喜欢

转载自www.cnblogs.com/hongyanohongyan/p/9891011.html