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);
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++)
31 {
32 if (min.compareTo(a[i]) > 0) min = a[i];
33 if (max.compareTo(a[i]) < 0) max = a[i];
34 }
35 return new Pair<>(min, max);
36 }
37 }
测试程序2:
l 编辑、调试运行教材315页 PairTest2,结合程序运行结果理解程序;
l 在泛型程序设计代码处添加相关注释;
l 掌握泛型方法、泛型变量限定的定义及用途。
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);
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 public static <T extends Comparable> Pair<T> minmax(T[] a)
35 {
36 if (a == null || a.length == 0) return null;
37 T min = a[0];
38 T max = a[0];
39 for (int i = 1; i < a.length; i++)
40 {
41 if (min.compareTo(a[i]) > 0) min = a[i];
42 if (max.compareTo(a[i]) < 0) max = a[i];
43 }
44 return new Pair<>(min, max);
45 }
46 }
package pair2;
/**
* @version 1.00 2004-05-10
* @author Cay Horstmann
*/
public class Pair<T>
{
private T first;
private T second;
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
测试程序3:
l 用调试运行教材335页 PairTest3,结合程序运行结果理解程序;
l 了解通配符类型的定义及用途。
package pair3;
/**
* @version 1.01 2012-01-26
* @author Cay Horstmann
*/
public class PairTest3
{
public static void main(String[] args)
{
Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
Pair<Manager> buddies = new Pair<>(ceo, cfo);
printBuddies(buddies);
ceo.setBonus(1000000);
cfo.setBonus(500000);
Manager[] managers = { ceo, cfo };
Pair<Employee> result = new Pair<>();
minmaxBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result.getSecond().getName());
maxminBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result.getSecond().getName());
}
public static void printBuddies(Pair<? extends Employee> p)
{
Employee first = p.getFirst();
Employee second = p.getSecond();
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
}
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
{
if (a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.getBonus() > a[i].getBonus()) min = a[i];
if (max.getBonus() < a[i].getBonus()) max = a[i];
}
result.setFirst(min);
result.setSecond(max);
}
public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
{
minmaxBonus(a, result);
PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
}
// Can't write public static <T super manager> ...
}
class PairAlg
{
public static boolean hasNulls(Pair<?> p)
{
return p.getFirst() == null || p.getSecond() == null;
}
public static void swap(Pair<?> p) { swapHelper(p); }
public static <T> void swapHelper(Pair<T> p)
{
T t = p.getFirst();
p.setFirst(p.getSecond());
p.setSecond(t);
}
}
package pair3;
/**
* @version 1.00 2004-05-10
* @author Cay Horstmann
*/
public class Pair<T>
{
private T first;
private T second;
public Pair() { first = null; second = null; }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
package pair3;
import java.time.*;
public class Employee
{
private String name;
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day)
{
this.name = name;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public LocalDate getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
}
package pair3;
public class Manager extends Employee
{
private double bonus;
/**
@param name the employee's name
@param salary the salary
@param year the hire year
@param month the hire month
@param day the hire day
*/
public Manager(String name, double salary, int year, int month, int day)
{
super(name, salary, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
public double getBonus()
{
return bonus;
}
}
实验2:编程练习:
编程练习1:实验九编程题总结
l 实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
1 package test1;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.util.ArrayList;
10 import java.util.Collections;
11 import java.util.Scanner;
12
13 public class Main{
14 private static ArrayList<Student> studentlist;
15 public static void main(String[] args) {
16 studentlist = new ArrayList<>();
17 Scanner scanner = new Scanner(System.in);
18 File file = new File("F:\\身份证号.txt");
19 try {
20 FileInputStream fis = new FileInputStream(file);
21 BufferedReader in = new BufferedReader(new InputStreamReader(fis));
22 String temp = null;
23 while ((temp = in.readLine()) != null) {
24
25 Scanner linescanner = new Scanner(temp);
26
27 linescanner.useDelimiter(" ");
28 String name = linescanner.next();
29 String number = linescanner.next();
30 String sex = linescanner.next();
31 String age = linescanner.next();
32 String province =linescanner.nextLine();
33 Student student = new Student();
34 student.setName(name);
35 student.setnumber(number);
36 student.setsex(sex);
37 int a = Integer.parseInt(age);
38 student.setage(a);
39 student.setprovince(province);
40 studentlist.add(student);
41
42 }
43 } catch (FileNotFoundException e) {
44 System.out.println("学生信息文件找不到");
45 e.printStackTrace();
46 } catch (IOException e) {
47 System.out.println("学生信息文件读取错误");
48 e.printStackTrace();
49 }
50 boolean isTrue = true;
51 while (isTrue) {
52 System.out.println("选择你的操作,输入正确格式的选项");
53 System.out.println("A.按姓名字典排序");
54 System.out.println("B.输出年龄最大和年龄最小的人");
55 System.out.println("C.寻找老乡");
56 System.out.println("D.寻找年龄相近的人");
57 System.out.println("F.退出");
58 String m = scanner.next();
59 switch (m) {
60 case "A":
61 Collections.sort(studentlist);
62 System.out.println(studentlist.toString());
63 break;
64 case "B":
65 int max=0,min=100;
66 int j,k1 = 0,k2=0;
67 for(int i=1;i<studentlist.size();i++)
68 {
69 j=studentlist.get(i).getage();
70 if(j>max)
71 {
72 max=j;
73 k1=i;
74 }
75 if(j<min)
76 {
77 min=j;
78 k2=i;
79 }
80
81 }
82 System.out.println("年龄最大:"+studentlist.get(k1));
83 System.out.println("年龄最小:"+studentlist.get(k2));
84 break;
85 case "C":
86 System.out.println("老家?");
87 String find = scanner.next();
88 String place=find.substring(0,3);
89 for (int i = 0; i <studentlist.size(); i++)
90 {
91 if(studentlist.get(i).getprovince().substring(1,4).equals(place))
92 System.out.println("老乡"+studentlist.get(i));
93 }
94 break;
95
96 case "D":
97 System.out.println("年龄:");
98 int yourage = scanner.nextInt();
99 int near=agenear(yourage);
100 int value=yourage-studentlist.get(near).getage();
101 System.out.println(""+studentlist.get(near));
102 break;
103 case "F":
104 isTrue = false;
105 System.out.println("退出程序!");
106 break;
107 default:
108 System.out.println("输入有误");
109
110 }
111 }
112 }
113 public static int agenear(int age) {
114 int j=0,min=53,value=0,k=0;
115 for (int i = 0; i < studentlist.size(); i++)
116 {
117 value=studentlist.get(i).getage()-age;
118 if(value<0) value=-value;
119 if (value<min)
120 {
121 min=value;
122 k=i;
123 }
124 }
125 return k;
126 }
127
128 }
1 package test1;
2
3 public class Student implements Comparable<Student> {
4
5 private String name;
6 private String number ;
7 private String sex ;
8 private int age;
9 private String province;
10
11 public String getName() {
12 return name;
13 }
14 public void setName(String name) {
15 this.name = name;
16 }
17 public String getnumber() {
18 return number;
19 }
20 public void setnumber(String number) {
21 this.number = number;
22 }
23 public String getsex() {
24 return sex ;
25 }
26 public void setsex(String sex ) {
27 this.sex =sex ;
28 }
29 public int getage() {
30
31 return age;
32 }
33 public void setage(int age) {
34 // int a = Integer.parseInt(age);
35 this.age= age;
36 }
37
38 public String getprovince() {
39 return province;
40 }
41 public void setprovince(String province) {
42 this.province=province ;
43 }
44
45 public int compareTo(Student o) {
46 return this.name.compareTo(o.getName());
47 }
48
49 public String toString() {
50 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
51 }
52 }
总体结构:
程序有一个主类和一个子类。
模块说明:
主类涉及到对文件的读入操作,所以要用try...catch语句进行异常处理。还有选择语句。
子类是对接口Comparable的实现。主要用来返回学生的信息。
目前程序设计的困难:
对文件的读写操作不熟悉,不知道如何进行排序以及查找。
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。


1 package shiyan;
2 import java.util.Scanner;
3 import java.io.PrintWriter;
4
5 public class Main {
6 public static void main(String[] args) throws Exception{
7 Scanner in=new Scanner(System.in);
8 PrintWriter output=new PrintWriter("E:/test.txt");
9 int sum=0;
10 jisuanji js=new jisuanji();
11 for (int i = 0; i < 10; i++) {
12 int a = (int) Math.round(Math.random() * 100);
13 int b = (int) Math.round(Math.random() * 100);
14 int n = (int) Math.round(Math.random() * 3);
15
16 switch(n)
17 {
18 case 1:
19 System.out.println(a+"/"+b+"=");
20 while(b==0){
21 b = (int) Math.round(Math.random() * 100);
22 }
23 double c = in.nextDouble();
24 output.println(a+"/"+b+"="+c);
25 if (c == js.chu(a,b)) {
26 sum += 10;
27 System.out.println("答案正确");
28 }
29 else {
30 System.out.println("答案错误");
31 }
32
33 break;
34
35 case 2:
36 System.out.println(a+"*"+b+"=");
37 int c1 = in.nextInt();
38 output.println(a+"*"+b+"="+c1);
39 if (c1 == js.chen(a, b)) {
40 sum += 10;
41 System.out.println("答案正确");
42 }
43 else {
44 System.out.println("答案错误");
45 }
46 break;
47 case 3:
48 System.out.println(a+"+"+b+"=");
49 int c2 = in.nextInt();
50 output.println(a+"+"+b+"="+c2);
51 if (c2 == js.jia(a, b)) {
52 sum += 10;
53 System.out.println("答案正确");
54 }
55 else {
56 System.out.println("答案错误");
57 }
58
59 break ;
60 case 4:
61 System.out.println(a+"-"+b+"=");
62 int c3 = in.nextInt();
63 output.println(a+"-"+b+"="+c3);
64 if (c3 == js.jian(a,b)) {
65 sum += 10;
66 System.out.println("答案正确");
67 }
68 else {
69 System.out.println("答案错误");
70 }
71 break ;
72
73 }
74
75 }
76 System.out.println("成绩"+sum);
77 output.println("成绩:"+sum);
78 output.close();
79 }
80 }


1 package shiyan;
2
3 public class jisuanji {
4 private int a;
5 private int b;
6 public int jia(int a,int b)
7 {
8 return a+b;
9 }
10 public int jian(int a,int b)
11 {
12 return a-b;
13 }
14 public int chen(int a,int b)
15 {
16 return a*b;
17 }
18 public int chu(int a,int b)
19 {
20 if(b==0)
21 {
22 return 0;
23 }
24 else
25 return a/b;
26 }
27 }
总体结构:有一个主类和一个子类。
模块说明:主类里涉及文件的输出和异常处理,子类是实现计算器功能的算法。
困难:不熟悉写出到文件的操作,导致程序编写困难。生成的减法和除法运算题不适应小学生的能力。
编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。


1 package shiyan;
2 import java.util.Scanner;
3 import java.io.FileNotFoundException;
4 import java.io.PrintWriter;
5
6 public class Main {
7 public static void main(String[] args) {
8 Scanner in=new Scanner(System.in);
9 PrintWriter output = null;
10 try {
11 output = new PrintWriter("E:/test.txt");
12 } catch (FileNotFoundException e) {
13 // TODO 自动生成的 catch 块
14 System.out.println("文件输出失败");
15 e.printStackTrace();
16 }
17 int sum=0;
18 jisuanji js=new jisuanji();
19 for (int i = 0; i < 10; i++) {
20 int a = (int) Math.round(Math.random() * 100);
21 int b = (int) Math.round(Math.random() * 100);
22 int n = (int) Math.round(Math.random() * 4 );
23
24 switch(n)
25 {
26 case 1:
27 System.out.println(a+"/"+b+"=");
28 while(b==0){
29 b = (int) Math.round(Math.random() * 100);
30 }
31 while(a%b!=0) {
32 a = (int) Math.round(Math.random() * 100);
33 b = (int) Math.round(Math.random() * 100);
34 }
35 double c = in.nextDouble();
36 output.println(a+"/"+b+"="+c);
37 if (c == js.chu(a,b)) {
38 sum += 10;
39 System.out.println("答案正确");
40 }
41 else {
42 System.out.println("答案错误");
43 }
44
45 break;
46
47 case 2:
48 System.out.println(a+"*"+b+"=");
49 int c1 = in.nextInt();
50 output.println(a+"*"+b+"="+c1);
51 if (c1 == js.chen(a, b)) {
52 sum += 10;
53 System.out.println("答案正确");
54 }
55 else {
56 System.out.println("答案错误");
57 }
58 break;
59 case 3:
60 System.out.println(a+"+"+b+"=");
61 int c2 = in.nextInt();
62 output.println(a+"+"+b+"="+c2);
63 if (c2 == js.jia(a, b)) {
64 sum += 10;
65 System.out.println("答案正确");
66 }
67 else {
68 System.out.println("答案错误");
69 }
70
71 break ;
72 case 4:
73 System.out.println(a+"-"+b+"=");
74 while(a<b) {
75 a = (int) Math.round(Math.random() * 100);
76 b = (int) Math.round(Math.random() * 100);
77 }
78 int c3 = in.nextInt();
79 output.println(a+"-"+b+"="+c3);
80 if (c3 == js.jian(a,b)) {
81 sum += 10;
82 System.out.println("答案正确");
83 }
84 else {
85 System.out.println("答案错误");
86 }
87 break ;
88
89 }
90
91 }
92 System.out.println("成绩"+sum);
93 output.println("成绩:"+sum);
94 output.close();
95 }
96 }


1 package shiyan;
2
3 public class jisuanji<T> {
4 private T a;
5 private T b;
6 public jisuanji() {
7 a=null;
8 b=null;
9 }
10 public jisuanji(T a,T b) {
11 this.a=a;
12 this.b=b;
13 }
14 public int jia(int a,int b)
15 {
16 return a+b;
17 }
18 public int jian(int a,int b)
19 {
20 return a-b;
21 }
22 public int chen(int a,int b)
23 {
24 return a*b;
25 }
26 public int chu(int a,int b)
27 {
28 if(b!=0&&a%b==0)
29 return a/b;
30 else
31 return 0;
32 }
33 }
实验总结:
这次实验加深了对实验9编程题的理解,改进了其中的错误。学会了泛型类的设计,但是通配符还是有些不理解的地方。
来源:oschina
链接:https://my.oschina.net/u/4263828/blog/4149872