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" };//初始化String对象数组 Pair<String> mm = ArrayAlg.minmax(words);//通过类名调用minmax方法 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)//实例化的一个Pair类对象 { 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];//字符串对象比较,通过ASCII码比较 if (max.compareTo(a[i]) < 0) max = a[i]; } return new Pair<>(min, max);//泛型类作为返回值 } }
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; } }
测试程序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对象数组 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);//通过类名调用minmax方法 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); } }
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,结合程序运行结果理解程序;
了解通配符类型的定义及用途。
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类对象 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); //swapHelper捕获通配符类型 } // 不能写公共静态 <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; 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; 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; /** * @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; } }
实验2:编程练习:
编程练习1:实验九编程题总结
实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
程序总体结构说明:定义了一个主类check和一个接口
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.Collections; import java.util.Scanner; public class Check{ private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("C:Users不染Desktop身份证号.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 number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String province =linescanner.nextLine(); Student student = new Student(); student.setName(name); student.setnumber(number); student.setsex(sex); int a = Integer.parseInt(age); student.setage(a); student.setprovince(province); studentlist.add(student); } } catch (FileNotFoundException e) { System.out.println("学生信息文件找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("学生信息文件读取错误"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("选择你的操作,输入正确格式的选项"); System.out.println("1.按姓名字典序输出人员信息"); System.out.println("2.输出年龄最大和年龄最小的人"); System.out.println("3.查找老乡"); System.out.println("4.查找年龄相近的人"); System.out.println("5.退出"); String m = scanner.next(); switch (m) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max=0,min=100; int j,k1 = 0,k2=0; for(int i=1;i<studentlist.size();i++) { j=studentlist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年龄最大:"+studentlist.get(k1)); System.out.println("年龄最小:"+studentlist.get(k2)); break; case "3": System.out.println("输入省份"); String find = scanner.next(); String place=find.substring(0,3); for (int i = 0; i <studentlist.size(); i++) { if(studentlist.get(i).getprovince().substring(1,4).equals(place)) System.out.println("老乡"+studentlist.get(i)); } break; case "4": System.out.println("年龄:"); int yourage = scanner.nextInt(); int near=agenear(yourage); int value=yourage-studentlist.get(near).getage(); System.out.println(""+studentlist.get(near)); break; case "5": isTrue = false; System.out.println("退出程序!"); break; default: System.out.println("输入有误"); } } } public static int agenear(int age) { int j=0,min=53,value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { value=studentlist.get(i).getage()-age; if(value<0) value=-value; if (value<min) { min=value; k=i; } } return k; } }
public class Student implements Comparable<Student> { private String name; private String number ; private String sex ; private int age; private String province; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return number; } public void setnumber(String number) { this.number = number; } public String getsex() { return sex ; } public void setsex(String sex ) { this.sex =sex ; } public int getage() { return age; } public void setage(int age) { // int a = Integer.parseInt(age); this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } public int compareTo(Student o) { return this.name.compareTo(o.getName()); } public String toString() { return name+" "+sex+" "+age+" "+number+" "+province+" "; } }
程序设计存在的困难与问题:最大的问题是,拿到一个问题,不知道从哪下手,缺乏大量的练习。就上一个练习来说,只会用单一的抛出异常来处理。
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
程序总体结构说明:主类Caculator和Caculator1类。
import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Caculator { public static void main(String[] args) { Scanner in = new Scanner(System.in); Caculator1 computing=new Caculator1(); PrintWriter output = null; try { output = new PrintWriter("Caculator.txt"); } catch (Exception e) { } int sum = 0; for (int i = 1; i < 11; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int s = (int) Math.round(Math.random() * 3); switch(s) { case 1: System.out.println(i+": "+a+"/"+b+"="); while(b==0){ b = (int) Math.round(Math.random() * 100); } double c = in.nextDouble(); output.println(a+"/"+b+"="+c); if (c == (double)computing.division(a, b)) { sum += 10; System.out.println("T"); } else { System.out.println("F"); } break; case 2: System.out.println(i+": "+a+"*"+b+"="); int c1 = in.nextInt(); output.println(a+"*"+b+"="+c1); if (c1 == computing.multiplication(a, b)) { sum += 10; System.out.println("T"); } else { System.out.println("F"); } break; case 3: System.out.println(i+": "+a+"+"+b+"="); int c2 = in.nextInt(); output.println(a+"+"+b+"="+c2); if (c2 == computing.addition(a, b)) { sum += 10; System.out.println("T"); } else { System.out.println("F"); } break ; case 4: System.out.println(i+": "+a+"-"+b+"="); int c3 = in.nextInt(); output.println(a+"-"+b+"="+c3); if (c3 == computing.subtraction(a, b)) { sum += 10; System.out.println("T"); } else { System.out.println("F"); } break ; } } System.out.println("scores:"+sum); output.println("scores:"+sum); output.close(); } } class Caculator1 { private int a; private int b; public int addition(int a,int b) { return a+b; } public int subtraction(int a,int b) { if((a-b)<0) return 0; else return a-b; } public int multiplication(int a,int b) { return a*b; } public int division(int a,int b) { if(b!=0) return a/b; else return 0; } }
问题:数据类型应用还不到位,代码不够精炼。
编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。
import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Suanshu1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); Suanshu ss = new Suanshu(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); } catch (FileNotFoundException e) { System.out.println("文件夹输出失败"); e.printStackTrace(); } 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 m; Random rand = new Random(); m = (int) rand.nextInt(4) + 1; System.out.println("随机生成的四则运算类型:" + m); switch (m) { case 1: a = b + (int) Math.round(Math.random() * 100); 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 c0 = in.nextInt(); out.println(a + "/" + b + "=" + c0); if (c0 == ss.chufa(a, b)) { sum += 10; System.out.println("right!"); } else { System.out.println("error!"); } break; case 2: System.out.println(i + " " + a + "*" + b + "="); int c = in.nextInt(); out.println(a + "*" + b + "=" + c); if (c == ss.chengfa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; case 3: System.out.println(i + " " + a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == ss.jiafa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; case 4: 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 == ss.jianfa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; } } System.out.println("最后得分" + sum); out.println("最后得分" + sum); out.close(); } }
public class Suanshu<T> { private T a; private T b; public Suanshu() { a = null; b = null; } public Suanshu(T a, T b) { this.a = a; this.b = b; } public int jiafa(int a,int b) { return a + b; } public int jianfa(int a, int b) { return a - b; } public int chengfa(int a, int b) { return a * b; } public int chufa(int a, int b) { if (b != 0 && a%b==0) return a / b; else return 0; } }
三、实验总结
这周的实验有对上周实验的反思,我发现了很多不足。首先接手问题之后的思路不清晰,其次代码编写不够,所以代码很冗杂。这周泛型设计的学习,了解到泛型类具备可重用性、类型安全和效率等性质,是程序性能得到提升。课下我还需继续努力。