一、理论知识学习部分
泛型类的约束与局限性:
不能用基本类型实例化类型参数
运行时类型查询只适用于原始类型
不能抛出也不能捕获泛型类实例
参数化类型的数组不合法
不能实例化类型变量
泛型类的静态上下文中类型变量无效
注意擦除后的冲突
Java 中泛型类不具协变性。如果能够将List<Integer>赋给List<Number>。那么下面的代码就允许将非Integer的内容放入List<Integer>:
List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));
泛型类可扩展或实现其它的泛型类。例如,
ArrayList<T>类实现List<T>接口。这意味着,一个ArrayList<Manager> 可以被转换为一个List<Manager>。
通配符
– “?”符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的。T表示一种未知类型,而“?”表示任何一种类型。这种通配符一般有以下三种用法:
– 单独的?,用于表示任何类型。
– ? extends type,表示带有上界。
– ? super type,表示带有下界。
定义一个泛型类时,在“<>”内定义形式类型参数,例如:“class TestGeneric<K, V>”,其中“K” , “V”不代表值,而是表示类型。
实例化泛型对象的时候,一定要在类名后面指定类型参数的值(类型),一共要有两次书写。例如:
TestGeneric<String, String> t
=new TestGeneric<String, String>();
泛型中<T extends Object>, extends并不代表继承,它是类型范围限制。
泛型类不是协变的。
实验十 泛型程序设计技术
实验时间 2018-11-1
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> //引入类型变量T { private T first;//运用类型变量T 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 = { "ary", "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)//调用静态minmax方法 { 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];//compareTo方法比较两个字符串
if (max.compareTo(a[i]) < 0) max = a[i]; } return new Pair<>(min, max);//用一个Pair对象返回两个结果 } }
测试程序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(1907, 12, 9), // G. Hopper LocalDate.of(1834, 12, 10), // A. Lovelace LocalDate.of(1923, 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)// 对类型变量T进行限定,将T
限制为实现了Comparable
接口的类:<T extends Comparable>
。 { 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的任何一种类型
{ 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))//?是通配符,表明参数的类型是下界为manager的任何一种类型
{ 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)//?是通配符,表明参数的类型是下界为manager的任何一种类型
{ 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:实验九编程题总结
l 实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
程序总体结构:主类Test和Citizen类
模块说明:
主类Test:文件的读取,根据实验要求编辑相关代码。
Citizen类:对所需数据进行具体的处理。
存在的问题:文件读入时在文件的读取方面存在一定的问题,在数据处理方面的转换也有相应的问题。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;//对集合进行排序、查找、修改等;
public class Test {
private static ArrayList<Citizen> citizenlist;
public static void main(String[] args) {
citizenlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
//读文件
File file = new File("E:/java/身份证号.txt");
//异常捕获
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String id = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String birthplace = linescanner.nextLine();
Citizen citizen = new Citizen();
citizen.setName(name);
citizen.setId(id);
citizen.setSex(sex);
// 将字符串转换成10进制数
int ag = Integer.parseInt(age);
citizen.setage(ag);
citizen.setBirthplace(birthplace);
citizenlist.add(citizen);
}
} catch (FileNotFoundException e) {
System.out.println("信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
//根据题目要求编写相关代码
while (isTrue) {
System.out.println("1.按姓名字典序输出人员信息");
System.out.println("2.查询最大年龄的人员信息、查询最小年龄人员信息");
System.out.println("3.查询人员中是否查询人员中是否有你的同乡");
System.out.println("4.输入你的年龄,查询文件中年龄与你最近人的姓名、身份证号、年龄、性别和出生地");
System.out.println("5.退出");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort(citizenlist);
System.out.println(citizenlist.toString());
break;
case 2:
int max = 0, min = 100;
int m, k1 = 0, k2 = 0;
for (int i = 1; i < citizenlist.size(); i++) {
m = citizenlist.get(i).getage();
if (m > max) {
max = m;
k1 = i;
}
if (m < min) {
min = m;
k2 = i;
}
}
System.out.println("年龄最大:" + citizenlist.get(k1));
System.out.println("年龄最小:" + citizenlist.get(k2));
break;
case 3:
System.out.println("出生地:");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place))
System.out.println("出生地" + citizenlist.get(i));
}
break;
case 4:
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near = peer(yourage);
int j = yourage - citizenlist.get(near).getage();
System.out.println("" + citizenlist.get(near));
break;
case 5:
isTrue = false;
System.out.println("程序已退出!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int peer(int age) {
int flag = 0;
int min = 53, j = 0;
for (int i = 0; i < citizenlist.size(); i++) {
j = citizenlist.get(i).getage() - age;
if (j < 0)
j = -j;
if (j < min) {
min = j;
flag = i;
}
}
return flag;
}
}
public class Citizen implements Comparable<Citizen> {
private String name;
private String id;
private String sex;
private int age;
private String birthplace;
//对数据进行相关处理
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public String getBirthplace() {
return birthplace;
}
public void setBirthplace(String birthplace) {
this.birthplace = birthplace;
}
public int compareTo(Citizen other) {
return this.name.compareTo(other.getName());
}
public String toString() {
return name + " " + sex + " " + age + " " + id + " " + birthplace + "
";
}
}
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
程序总体结构:主类Calculator
模块说明:文件输出、生成四则运算计算器。
存在的问题:不能将输出结果生成相应的文件。
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
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();
}
}
}
编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。
import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class calculator { 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; }
实验总结:
理解掌握了泛型类的定义与使用,泛型方法的声明与使用;泛型接口的定义与实现;此外,对上次实验的总结反思方面,从中发现了一些问题,尤其是四则运算的编程,相比上次实验,从中认识到了很多不足,也在程序结果的导成相应文件方面也有很大的问题,希望在这周的学习中通过老师的指导将这方面在提升一下。在这次实验的过程中最大的收获就是通过刚学习的泛型类,能使四则运算的编程更加的全面,可以实现各种数据类型的运算。有了很大的提升。