实验十 泛型程序设计技术
理论知识:
泛型也称为参数化类型,就是在定义类、方法、接口时,通过类型参数指示将要处理的对象类型。
.泛型程序设计:编写代码可以被很多不同类型的对象所重用。
.一个泛型类就是具有一个或多个类型变量的类,即创建用类型作为参数的类。
.Pair类引入了一个类型变量T,用尖括号(<>)括起来,并放在类名的后面。泛型类可以有多个类型变量。
.类定义中的类型变量用于指定方法的返回类型以及域、局部变量的类型。
.除了泛型类外,还可以只单独定义一个方法作为泛型方法,用于指定方法参数或者返回值为泛型类型,留待方法调用时确定。泛型方法可以声明在泛型类中,也可以声明在普通类中。
泛型变量上界:extends关键字所声明的上界既可以是一个类,也可以是一个接口。
.一个类型变量或通配符可以有多个限定,限定类型用“&”分割。
.泛型变量下界:通过使用super关键字可以固定泛型参数的类型为某种类型或者其超类。当程序希望为一个方法的参数限定类型时,通常可以使用下限通配符。
.Java中的数组是协变的。例如:Integer扩展了Number,那么在要求Number[]的地方完全可以传递或者赋予Integer[],Number[]也是Integer[]的超类型。Employee 是Manager 的超类, 因此可以将一个Manager[]数组赋给一个类型为Employee[]的变量。
注:泛型类型的数组不是协变的。
1、实验目的与要求
(1) 理解泛型概念;
(2) 掌握泛型类的定义与使用;
(3) 掌握泛型方法的声明与使用;
(4) 掌握泛型接口的定义与实现;
(5)了解泛型程序设计,理解其用途。
2、实验内容和步骤
实验1: 导入第8章示例程序,测试程序并进行代码注释。
测试程序1:
l 编辑、调试、运行教材311、312页 代码,结合程序运行结果理解程序;
l 在泛型类定义及使用代码处添加注释;
l 掌握泛型类的定义及使用。
package pair1;
/**
* @version 1.01 2012-01-26
* @author Cay Horstmann
*/
public class PairTest1
{
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb" };
Pair<String> mm = ArrayAlg.minmax(words);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
}
class ArrayAlg
{
/**
* Gets the minimum and maximum of an array of strings.
* @param a an array of strings
* @return a pair with the min and max value, or null if a is null or empty
*/
public static Pair<String> minmax(String[] a)
{
if (a == null || a.length == 0) return null;
String min = a[0];
String max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
}
结果图:

测试程序2:
l 编辑、调试运行教材315页 PairTest2,结合程序运行结果理解程序;
l 在泛型程序设计代码处添加相关注释;
l 掌握泛型方法、泛型变量限定的定义及用途。
package pair2;
import java.time.*;
/**
* @version 1.02 2015-06-21
* @author Cay Horstmann
*/
public class PairTest2
{
public static void main(String[] args)
{
LocalDate[] birthdays =
{
LocalDate.of(1906, 12, 9), // G. Hopper
LocalDate.of(1815, 12, 10), // A. Lovelace
LocalDate.of(1903, 12, 3), // J. von Neumann
LocalDate.of(1910, 6, 22), // K. Zuse
};
Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
}
class ArrayAlg
{
/**
Gets the minimum and maximum of an array of objects of type T.
@param a an array of objects of type T
@return a pair with the min and max value, or null if a is
null or empty
*/
public static <T extends Comparable> Pair<T> minmax(T[] a)
{
if (a == null || a.length == 0) return null;
T min = a[0];
T max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
}
结果图:

测试程序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);
}
}
结果图:

实验2:编程练习:
编程练习1:实验九编程题总结
l 实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
import java.io;
2 import java.io.File;
3 import java.io.FileInputStream;
4 import java.io.FileNotFoundException;
5 import java.io.IOException;
6 import java.io.InputStreamReader;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
10 import java.util.Scanner;
11
12 public class Test{
13 private static ArrayList<Student> studentlist;
14 public static void main(String[] args) {
15 studentlist = new ArrayList<>();
16 Scanner scanner = new Scanner(System.in);
17 File file = new File("C:\下载\身份证号.txt");
18 try {
19 FileInputStream fis = new FileInputStream(file);
20 BufferedReader in = new BufferedReader(new InputStreamReader(fis));
21 String temp = null;
22 while ((temp = in.readLine()) != null) {
23
24 Scanner linescanner = new Scanner(temp);
25
26 linescanner.useDelimiter(" ");
27 String name = linescanner.next();
28 String number = linescanner.next();
29 String sex = linescanner.next();
30 String age = linescanner.next();
31 String province =linescanner.nextLine();
32 Student student = new Student();
33 student.setName(name);
34 student.setnumber(number);
35 student.setsex(sex);
36 int a = Integer.parseInt(age);
37 student.setage(a);
38 student.setprovince(province);
39 studentlist.add(student);
40
41 }
42 } catch (FileNotFoundException e) {
43 System.out.println("学生信息文件找不到");
44 e.printStackTrace();
45 } catch (IOException e) {
46 System.out.println("学生信息文件读取错误");
47 e.printStackTrace();
48 }
49 boolean isTrue = true;
50 while (isTrue) {
51 System.out.println("选择你的操作,输入正确格式的选项");
52 System.out.println("1.按姓名字典序输出人员信息");
53 System.out.println("2.输出年龄最大和年龄最小的人");
54 System.out.println("3.查找老乡");
55 System.out.println("4.查找年龄相近的人");
56 System.out.println("5.退出");
57 String m = scanner.next();
58 switch (m) {
59 case "1":
60 Collections.sort(studentlist);
61 System.out.println(studentlist.toString());
62 break;
63 case "2":
64 int max=0,min=100;
65 int j,k1 = 0,k2=0;
66 for(int i=1;i<studentlist.size();i++)
67 {
68 j=studentlist.get(i).getage();
69 if(j>max)
70 {
71 max=j;
72 k1=i;
73 }
74 if(j<min)
75 {
76 min=j;
77 k2=i;
78 }
79
80 }
81 System.out.println("年龄最大:"+studentlist.get(k1));
82 System.out.println("年龄最小:"+studentlist.get(k2));
83 break;
84 case "3":
85 System.out.println("输入省份");
86 String find = scanner.next();
87 String place=find.substring(0,3);
88 for (int i = 0; i <studentlist.size(); i++)
89 {
90 if(studentlist.get(i).getprovince().substring(1,4).equals(place))
91 System.out.println("老乡"+studentlist.get(i));
92 }
93 break;
94
95 case "4":
96 System.out.println("年龄:");
97 int yourage = scanner.nextInt();
98 int near=agenear(yourage);
99 int value=yourage-studentlist.get(near).getage();
100 System.out.println(""+studentlist.get(near));
101 break;
102 case "5":
103 isTrue = false;
104 System.out.println("退出程序!");
105 break;
106 default:
107 System.out.println("输入有误");
108
109 }
110 }
111 }
112 public static int agenear(int age) {
113 int j=0,min=53,value=0,k=0;
114 for (int i = 0; i < studentlist.size(); i++)
115 {
116 value=studentlist.get(i).getage()-age;
117 if(value<0) value=-value;
118 if (value<min)
119 {
120 min=value;
121 k=i;
122 }
123 }
124 return k;
125 }
126
127 }
public class Student implements Comparable<Student> {
2
3 private String name;
4 private String number ;
5 private String sex ;
6 private int age;
7 private String province;
8
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public String getnumber() {
16 return number;
17 }
18 public void setnumber(String number) {
19 this.number = number;
20 }
21 public String getsex() {
22 return sex ;
23 }
24 public void setsex(String sex ) {
25 this.sex =sex ;
26 }
27 public int getage() {
28
29 return age;
30 }
31 public void setage(int age) {
32 // int a = Integer.parseInt(age);
33 this.age= age;
34 }
35
36 public String getprovince() {
37 return province;
38 }
39 public void setprovince(String province) {
40 this.province=province ;
41 }
42
43 public int compareTo(Student o) {
44 return this.name.compareTo(o.getName());
45 }
46
47 public String toString() {
48 return name+" "+sex+" "+age+" "+number+" "+province+"
";
49 }
50 }
实验中主类是:class test
子类:class Student
在实验中进行写代码时有时候不知道怎么去定义这个代码,怎样把想的东西用代码表示;
缺少练习,文件的读取上也有一些问题。
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
package 运算;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
// 用户的答案要从键盘输入,因此需要一个键盘输入流
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
// 定义一个变量用来统计得分
int sum = 0;
// 通过循环生成10道题
for (int i = 0; i < 10; i++) {
// 随机生成两个10以内的随机数作为被除数和除数
int a = (int) Math.round(Math.random() * 10);
int b = (int) Math.round(Math.random() * 10);
System.out.println(a + "/" + b + "=");
// 定义一个整数用来接收用户输入的答案
int c = in.nextInt();
// 判断用户输入的答案是否正确,正确给10分,错误不给分
if (c == a / b) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
}
//输出用户的成绩
System.out.println("你的得分为"+sum);
}
}
package 运算;
public class Yuns {
public int add(int a,int b)
{
return a+b;
}
public int reduce(int a,int b)
{
if((a-b)>0)
return a-b;
else return 0;
}
public int multiply(int a,int b)
{
return a*b;
}
public int devision(int a,int b)
{
if(b!=0)
return a/b;
else return 0;
}
主类:demo
在这个实验中在最后进行运行时出现0时在不运行的问题还没解决;
编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。
package 运算;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Count count=new Count();
PrintWriter out = null;
try {
out = new PrintWriter("test.txt");
int sum = 0;
for (int i = 1; i <=10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int menu = (int) Math.round(Math.random() * 3);
switch (menu) {
case 0:
System.out.println(i+":"+a + "+" + b + "=");
int c1 = in.nextInt();
out.println(a + "+" + b + "=" + c1);
if (c1 == (a + b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 1:
while (a < b) {
b = (int) Math.round(Math.random() * 100);
}
System.out.println(i+":"+a + "-" + b + "=");
int c2 = in.nextInt();
out.println(a + "-" + b + "=" + c2);
if (c2 == (a - b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(i+":"+a + "*" + b + "=");
int c3 = in.nextInt();
out.println(a + "*" + b + "=" + c3);
if (c3 == a * b) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
while(b == 0){
b = (int) Math.round(Math.random() * 100);
}
while(a % b != 0){
a = (int) Math.round(Math.random() * 100);
}
System.out.println(i+":"+a + "/" + b + "=");
int c4 = in.nextInt();
if (c4 == a / b) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
}
}
System.out.println("你的得分为" + sum);
out.println("你的得分为" + sum);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public class Count<T> {
private T a;
private T b;
public Count() {
a=null;
b=null;
}
public Count(T a,T b) {
this.a=a;
this.b=b;
}
public int count1(int a,int b) {
return a+b;
}
public int count2(int a,int b) {
return a-b;
}
public int count3(int a,int b) {
return a*b;
}
public int count4(int a,int b) {
return a/b;
}
}
结果图:

实验总结:在这次实验里把自己在实验中的遇到的问题都阐述了一遍,在进行了新的编程练习。