王海珍 201771010124《面向对象程序设计(Java)》第十周实验总结
第一部分:理论知识
主要内容: 什么是泛型程序设计 泛型类的声明及实例化的方法 泛型方法的定义 泛型接口的定义 泛型类型的继承规则 通配符类型及使用方法
1:泛型类的定义
(1) 一个泛型类(generic class)就是具有一个或多个类型变量的类,即创建用类型作为参数的类。如一个泛型类定义格式如下:class Generics<K,V>其中的K和V是类中的可变类型参数。如:
public class Pair{ 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;} }
(2)Pair类引入了一个类型变量T,用尖括号(<>)括起来,并放在类名的后面。泛型类可以有多个类型变量。例如:public class Pair<t, u=""> { … }
(3) 类定义中的类型变量用于指定方法的返回类型以及域、局部变量的类型。
2.泛型方法的声明 (1)泛型方法 – 除了泛型类外,还可以只单独定义一个方法作为泛型方法,用于指定方法参数或者返回值为泛型类型,留待方法调用时确定。 – 泛型方法可以声明在泛型类中,也可以声明在普通类中。
public class ArrayTool { public static void insert( E[] e, int i) { //请自己添加代码 } public static E valueAt( E[] e , int i) { //请自己添加代码 } }
3.泛型接口的定义 (1)定义 public interface IPool { T get(); int add(T t); }
(2)实现
public class GenericPool implements IPool { … }
public class GenericPool implements IPool
{ … }
4.泛型变量的限定 (1) 定义泛型变量的上界 public class NumberGeneric< T extends Number> (2) 泛型变量上界的说明 上述声明规定了NumberGeneric类所能处理的泛型变量类型需和Number有继承关系; extends关键字所声明的上界既可以是一个类,也可以是一个接口; (3)< T extends BoundingType> 表示T应该是绑定类型的子类型。 一个类型变量或通配符可以有多个限定,限定类型用“&”分割。例如:< T extends Comparable & Serializable > (4) 定义泛型变量的下界 List cards = new ArrayList(); (5) 泛型变量下界的说明 – 通过使用super关键字可以固定泛型参数的类型为某种类型或者其超类 – 当程序希望为一个方法的参数限定类型时,通常可以使用下限通配符
public static void sort(T[] a,Comparator c) { … }
5.通配符类型
通配符 – “?”符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的。T表示一种未知类型,而“?”表示任何一种类型。这种通配符一般有以下三种用法: – 单独的?,用于表示任何类型。 – ? extends type,表示带有上界。 – ? super type,表示带有下界。
1、实验目的与要求
(1) 理解泛型概念;
(2) 掌握泛型类的定义与使用;
(3) 掌握泛型方法的声明与使用;
(4) 掌握泛型接口的定义与实现;
(5)了解泛型程序设计,理解其用途。
2、实验内容和步骤
实验1: 导入第8章示例程序,测试程序并进行代码注释。
测试程序1:
l 编辑、调试、运行教材311、312页 代码,结合程序运行结果理解程序;
l 在泛型类定义及使用代码处添加注释;
l 掌握泛型类的定义及使用。
package pair1;
/**
* @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 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;
/**
* @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 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;
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;
}
}
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;
/**
* @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总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
1 package shiyan9;
2 import java.io.BufferedReader;
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.Collections;
11 import java.util.Scanner;
12
13
14 public class Search{
15
16 private static ArrayList<Person> Personlist1;
17 public static void main(String[] args) {
18
19
20
21 Personlist1 = new ArrayList<>();
22
23 Scanner scanner = new Scanner(System.in);
24 File file = new File("E:\\面向对象程序设计Java\\实验\\实验六\\身份证号.txt");
25
26 try {
27 FileInputStream F = new FileInputStream(file);
28 BufferedReader in = new BufferedReader(new InputStreamReader(F));
29 String temp = null;
30 while ((temp = in.readLine()) != null) {
31
32 Scanner linescanner = new Scanner(temp);
33
34 linescanner.useDelimiter(" ");
35 String name = linescanner.next();
36 String id = linescanner.next();
37 String sex = linescanner.next();
38 String age = linescanner.next();
39 String place =linescanner.nextLine();
40 Person Person = new Person();
41 Person.setname(name);
42 Person.setid(id);
43 Person.setsex(sex);
44 int a = Integer.parseInt(age);
45 Person.setage(a);
46 Person.setbirthplace(place);
47 Personlist1.add(Person);
48
49 }
50 } catch (FileNotFoundException e) {
51 System.out.println("查找不到信息");
52 e.printStackTrace();
53 } catch (IOException e) {
54 System.out.println("信息读取有误");
55 e.printStackTrace();
56 }
57 boolean isTrue = true;
58 while (isTrue) {
59 System.out.println("******************************************");
60 System.out.println("1:按姓名字典顺序输出信息;");
61 System.out.println("2:查询最大年龄与最小年龄人员信息;");
62 System.out.println("3:按省份找你的同乡;");
63 System.out.println("4:输入你的年龄,查询年龄与你最近人的信息;");
64 System.out.println("5:退出");
65 System.out.println("******************************************");
66 int type = scanner.nextInt();
67 switch (type) {
68 case 1:
69 Collections.sort(Personlist1);
70 System.out.println(Personlist1.toString());
71 break;
72 case 2:
73
74 int max=0,min=100;int j,k1 = 0,k2=0;
75 for(int i=1;i<Personlist1.size();i++)
76 {
77 j=Personlist1.get(i).getage();
78 if(j>max)
79 {
80 max=j;
81 k1=i;
82 }
83 if(j<min)
84 {
85 min=j;
86 k2=i;
87 }
88
89 }
90 System.out.println("年龄最大:"+Personlist1.get(k1));
91 System.out.println("年龄最小:"+Personlist1.get(k2));
92 break;
93 case 3:
94 System.out.println("place?");
95 String find = scanner.next();
96 String place=find.substring(0,3);
97 String place2=find.substring(0,3);
98 for (int i = 0; i <Personlist1.size(); i++)
99 {
100 if(Personlist1.get(i).getbirthplace().substring(1,4).equals(place))
101 {
102 System.out.println("你的同乡:"+Personlist1.get(i));
103 }
104 }
105
106 break;
107 case 4:
108 System.out.println("年龄:");
109 int yourage = scanner.nextInt();
110 int close=ageclose(yourage);
111 int d_value=yourage-Personlist1.get(close).getage();
112 System.out.println(""+Personlist1.get(close));
113
114 break;
115 case 5:
116 isTrue = false;
117 System.out.println("再见!");
118 break;
119 default:
120 System.out.println("输入有误");
121 }
122 }
123 }
124 public static int ageclose(int age) {
125 int m=0;
126 int max=53;
127 int d_value=0;
128 int k=0;
129 for (int i = 0; i < Personlist1.size(); i++)
130 {
131 d_value=Personlist1.get(i).getage()-age;
132 if(d_value<0) d_value=-d_value;
133 if (d_value<max)
134 {
135 max=d_value;
136 k=i;
137 }
138
139 } return k;
140
141 }
142
143
144
145 }
1 package shiyan9;
2
3
4 public class Person implements Comparable<Person> {
5 private String name;
6 private String id;
7 private int age;
8 private String sex;
9 private String birthplace;
10
11 public String getname() {
12 return name;
13 }
14 public void setname(String name) {
15 this.name = name;
16 }
17 public String getid() {
18 return id;
19 }
20 public void setid(String id) {
21 this.id= id;
22 }
23 public int getage() {
24
25 return age;
26 }
27 public void setage(int age) {
28 // int a = Integer.parseInt(age);
29 this.age= age;
30 }
31 public String getsex() {
32 return sex;
33 }
34 public void setsex(String sex) {
35 this.sex= sex;
36 }
37 public String getbirthplace() {
38 return birthplace;
39 }
40 public void setbirthplace(String birthplace) {
41 this.birthplace= birthplace;
42 }
43
44 public int compareTo(Person o) {
45 return this.name.compareTo(o.getname());
46
47 }
48
49 public String toString() {
50 return name+"\t"+sex+"\t"+age+"\t"+id+"\t";
51
52 }
53
54
55
56 }
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
1 package a;
2
3 import java.io.FileNotFoundException;
4 import java.io.PrintWriter;
5 import java.util.Scanner;
6
7 import org.w3c.dom.css.Counter;
8
9
10 public class Main{
11 public static void main(String[] args) {
12
13 Scanner in = new Scanner(System.in);
14 counter counter=new counter();
15 PrintWriter output = null;
16 try {
17 output = new PrintWriter("result.txt");
18 } catch (Exception e) {
19 //e.printStackTrace();
20 }
21 int sum = 0;
22
23 for (int i = 1; i < 11; i++) {
24 int a = (int) Math.round(Math.random() * 100);
25 int b = (int) Math.round(Math.random() * 100);
26 int type = (int) Math.round(Math.random() * 4);
27
28
29 switch(type)
30 {
31 case 1:
32 System.out.println(i+": "+a+"/"+b+"=");
33 while(b==0){
34 b = (int) Math.round(Math.random() * 100);
35 }
36 double c = in.nextDouble();
37 output.println(a+"/"+b+"="+c);
38 if (c == counter.Chu(a, b))
39 {
40 sum += 10;
41 System.out.println("恭喜答案正确!");
42 }
43 else {
44 System.out.println("答案错误!");
45 } break;
46
47 case 2:
48 System.out.println(i+": "+a+"*"+b+"=");
49 int c1 = in.nextInt();
50 output.println(a+"*"+b+"="+c1);
51 if (c1 == counter.Cheng(a, b)) {
52 sum += 10;
53 System.out.println("恭喜答案正确!");
54 }
55 else {
56 System.out.println("答案错误!");
57 }break;
58 case 3:
59 System.out.println(i+": "+a+"+"+b+"=");
60 int c2 = in.nextInt();
61 output.println(a+"+"+b+"="+c2);
62 if (c2 == counter.Jia(a, b)) {
63 sum += 10;
64 System.out.println("恭喜答案正确!");
65 }
66 else {
67 System.out.println("答案错误!");
68 }break ;
69 case 4:
70 System.out.println(i+": "+a+"-"+b+"=");
71 int c3 = in.nextInt();
72 output.println(a+"-"+b+"="+c3);
73 if (c3 == counter.Jian(a, b)) {
74 sum += 10;
75 System.out.println("恭喜答案正确!");
76 }
77 else {
78 System.out.println("答案错误!");
79 }break ;
80
81 }
82
83 }
84 System.out.println("成绩"+sum);
85 output.println("成绩:"+sum);
86 output.close();
87
88 }
89 }
1 package a;
2
3
4 public class counter {
5 private int a;
6 private int b;
7
8 public int Jia(int a,int b)
9 {
10 return a+b;
11 }
12 public int Jian(int a,int b)
13 {
14 if((a-b)<0)
15 return 0;
16 else
17 return a-b;
18 }
19 public int Cheng(int a,int b)
20 {
21 return a*b;
22 }
23 public int Chu(int a,int b)
24 {
25 if(b!=0)
26 return a/b;
27 else
28 return 0;
29 }
30
31
32 }
编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。
1 package a;
2
3 import java.io.FileNotFoundException;
4 import java.io.PrintWriter;
5 import java.util.Scanner;
6
7 //import org.w3c.dom.css.Counter;
8
9
10 public class Main{
11 public static void main(String[] args) {
12
13 Scanner in = new Scanner(System.in);
14 counter Counter=new counter();
15 PrintWriter output = null;
16 try {
17 output = new PrintWriter("result.txt");
18 } catch (Exception e) {
19 //e.printStackTrace();
20 }
21 int sum = 0;
22
23 for (int i = 1; i <=10; i++) {
24 int a = (int) Math.round(Math.random() * 100);
25 int b = (int) Math.round(Math.random() * 100);
26 int type = (int) Math.round(Math.random() * 4);
27
28
29 switch(type)
30 {
31 case 1:
32
33 System.out.println(i+": "+a+"/"+b+"=");
34 while(b== 0&& a%b!=0)
35 {
36 b = (int) Math.round(Math.random() * 100);
37 a = (int) Math.round(Math.random() * 100);
38 }
39
40 int c = in.nextInt();
41 output.println(a+"/"+b+"="+c);
42 if (c == Counter.Chu(a, b))
43 {
44 sum += 10;
45 System.out.println("恭喜答案正确!");
46 }
47 else {
48 System.out.println("答案错误!");
49 }
50 break;
51
52 case 2:
53 System.out.println(i+": "+a+"*"+b+"=");
54 int c1 = in.nextInt();
55 output.println(a+"*"+b+"="+c1);
56 if (c1 == Counter.Cheng(a, b)) {
57 sum += 10;
58 System.out.println("恭喜答案正确!");
59 }
60 else {
61 System.out.println("答案错误!");
62 }
63 break;
64 case 3:
65 System.out.println(i+": "+a+"+"+b+"=");
66 int c2 = in.nextInt();
67 output.println(a+"+"+b+"="+c2);
68
69 if (c2 == Counter.Jia(a, b)) {
70 sum += 10;
71 System.out.println("恭喜答案正确!");
72 }
73 else {
74 System.out.println("答案错误!");
75 }
76 break ;
77
78
79 case 4:
80
81 while (a < b) {
82 int x=0;
83 x=b;
84 b=a;
85 a=x;
86 }
87 System.out.println(i+": "+a+"-"+b+"=");
88 int c3 = in.nextInt();
89 output.println(a+"-"+b+"="+c3);
90 if (c3 == Counter.Jian(a, b))
91 {
92 sum += 10;
93 System.out.println("恭喜答案正确!");
94 }
95 else {
96 System.out.println("答案错误!");
97 }
98 break ;
99
100 }
101
102 }
103 System.out.println("成绩"+sum);
104 output.println("成绩:"+sum);
105 output.close();
106
107 }
108 }
1 package a;
2
3
4 public class counter<T>{
5 private T a;
6 private T b;
7
8 public counter(T a, T b) {
9 this.a = a;
10 this.b = b;
11 }
12
13 public counter() {
14 // TODO Auto-generated constructor stub
15 }
16
17 public int Jia(int a,int b)
18 {
19 return a+b;
20 }
21 public int Jian(int a,int b)
22 {
23 return a-b;
24
25
26 }
27 public int Cheng(int a,int b)
28 {
29 return a*b;
30 }
31 public int Chu(int a,int b)
32 {
33 if (b!= 0 && a%b==0)
34 return a / b;
35 else
36 return 0;
37
38 }
39
40
41 }
测试结果如下所示


第三部分 实验总结
本章节主要学习了泛型程序设计,泛型程序设计意味着编写代码可以被很多不同类型的对象所重用。而本章节的内容对我自己来说学起来还是存在许多问题的,所以下去还的多练多看书,尤其是关于本章节的泛型的使用等各个方面。
浙公网安备 33010602011771号