达拉草201771010105《面向对象程序设计(java)》第十周学习总结
达拉草201771010105《面向对象程序设计(java)》第十周学习总结
实验十 泛型程序设计技术
实验时间 2018-11-1
第一部分:理论知识
泛型:也称参数化类型(parameterizedtype), 就是在定义类、接口和方法时,通过类型参数指 示将要处理的对象类型。(如ArrayList类)
泛型程序设计(Genericprogramming):编写 代码可以被很多不同类型的对象所重用。
泛型类的定义:
1.一个泛型类(genericclass)就是具有一个或多 个类型变量的类,即创建用类型作为参数的类。 如一个泛型类定义格式如下: classGenerics<K,V> 其中的K和V是类中的可变类型参数。
2. Pair类引入了一个类型变量T,用尖括号(<>) 括起来,并放在类名的后面。
3.泛型类可以有多个类型变量。例如: publicclassPair<T,U>{…}
4.类定义中的类型变量用于指定方法的返回类型以 及域、局部变量的类型。
泛型方法:
1. 泛型方法 –除了泛型类外,还可以只单独定义一个方法作 为泛型方法,用于指定方法参数或者返回值为 泛型类型,留待方法调用时确定。
2.泛型方法可以声明在泛型类中,也可以声明在 普通类中。
通配符类型;
通配符 –“?”符号表明参数的类型可以是任何一种类 型,它和参数T的含义是有区别的。T表示一种 未知类型,而“?”表示任何一种类型。这种 通配符一般有以下三种用法:
1.单独的?,用于表示任何类型。
2.? extends type,表示带有上界。
3.? super type,表示带有下界。
泛型中<TextendsObject>,extends并不代表继 承,它是类型范围限制。
泛型类不是协变的。
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 }
程序运行结果如下;
测试程序3:
l 用调试运行教材335页 PairTest3,结合程序运行结果理解程序;
l 了解通配符类型的定义及用途。
1 package pair3; 2 3 import java.time.*; 4 5 public class Employee 6 { 7 private String name; 8 private double salary; 9 private LocalDate hireDay; 10 11 public Employee(String name, double salary, int year, int month, int day)//构造器 12 { 13 this.name = name; 14 this.salary = salary; 15 hireDay = LocalDate.of(year, month, day); 16 } 17 18 public String getName()//访问器 19 { 20 return name; 21 } 22 23 public double getSalary()//访问器 24 { 25 return salary; 26 } 27 28 public LocalDate getHireDay() 29 { 30 return hireDay; 31 } 32 33 public void raiseSalary(double byPercent) 34 { 35 double raise = salary * byPercent / 100; 36 salary += raise; 37 } 38 }
1 package pair3; 2 3 public class Manager extends Employee 4 { 5 private double bonus; 6 7 /** 8 @param name the employee's name 9 @param salary the salary 10 @param year the hire year 11 @param month the hire month 12 @param day the hire day 13 */ 14 public Manager(String name, double salary, int year, int month, int day) 15 { 16 super(name, salary, year, month, day); 17 bonus = 0; 18 } 19 20 public double getSalary()//访问器 21 { 22 double baseSalary = super.getSalary(); 23 return baseSalary + bonus; 24 } 25 26 public void setBonus(double b)//更改器 27 { 28 bonus = b; 29 } 30 31 public double getBonus() 32 { 33 return bonus; 34 } 35 }
1 package pair3; 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 pair3; 2 3 /** 4 * @version 1.01 2012-01-26 5 * @author Cay Horstmann 6 */ 7 public class PairTest3 8 { 9 public static void main(String[] args) 10 { 11 Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15); 12 Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15); 13 Pair<Manager> buddies = new Pair<>(ceo, cfo); 14 printBuddies(buddies); 15 16 ceo.setBonus(1000000); 17 cfo.setBonus(500000); 18 Manager[] managers = { ceo, cfo }; 19 20 Pair<Employee> result = new Pair<>(); 21 minmaxBonus(managers, result); 22 System.out.println("first: " + result.getFirst().getName() 23 + ", second: " + result.getSecond().getName()); 24 maxminBonus(managers, result); 25 System.out.println("first: " + result.getFirst().getName() 26 + ", second: " + result.getSecond().getName()); 27 } 28 29 public static void printBuddies(Pair<? extends Employee> p)//表明带有上界 30 { 31 Employee first = p.getFirst(); 32 Employee second = p.getSecond(); 33 System.out.println(first.getName() + " and " + second.getName() + " are buddies."); 34 } 35 36 public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)//表明带有下界 37 { 38 if (a.length == 0) return; 39 Manager min = a[0]; 40 Manager max = a[0]; 41 for (int i = 1; i < a.length; i++) 42 { 43 if (min.getBonus() > a[i].getBonus()) min = a[i]; 44 if (max.getBonus() < a[i].getBonus()) max = a[i]; 45 } 46 result.setFirst(min); 47 result.setSecond(max); 48 } 49 50 public static void maxminBonus(Manager[] a, Pair<? super Manager> result)//表明带有下界 51 { 52 minmaxBonus(a, result); 53 PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type 54 } 55 // Can't write public static <T super manager> ... 56 } 57 58 class PairAlg 59 { 60 public static boolean hasNulls(Pair<?> p) 61 { 62 return p.getFirst() == null || p.getSecond() == null; 63 } 64 65 public static void swap(Pair<?> p) { swapHelper(p); } 66 67 public static <T> void swapHelper(Pair<T> p) 68 { 69 T t = p.getFirst(); 70 p.setFirst(p.getSecond()); 71 p.setSecond(t); 72 } 73 }
程序运行结果如下:
实验2:编程练习:
编程练习1:实验九编程题总结
l 实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
1 import java.io.BufferedReader; 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 Moom{ 13 private static ArrayList<Mest> studentlist; 14 public static void main(String[] args) { 15 studentlist = new ArrayList<>(); 16 Scanner scanner = new Scanner(System.in); 17 File file = new File("D:\\身份证号.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 Mest student = new Mest(); 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 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("province"+studentlist.get(i)); 92 } 93 break; 94 95 case "4": 96 System.out.println("年龄:"); 97 int yourage = scanner.nextInt(); 98 int near=agematched(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 agematched(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 }
1 public class Mest implements Comparable<Mest> { 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 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(Mest o) { 44 return this.name.compareTo(o.getName()); 45 } 46 47 public String toString() { 48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; 49 } 50 51 }
程序总体结构说明和模块说明:程序分一个主类和一个Mest类,Mest类实现Comparable接口。
目前程序设计存在的困难与问题:对编写程序还有很多不懂得地方,文件捕获错误的代码用的不是很熟练。
l 实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。
1 package MM; 2 3 import java.util.Random; 4 import java.util.Scanner; 5 6 import java.io.FileNotFoundException; 7 8 import java.io.PrintWriter; 9 10 public class Demo{ 11 public static void main(String[] args) 12 { 13 14 MNM counter=new MNM();//与其它类建立联系 15 PrintWriter out=null; 16 try { 17 out=new PrintWriter("D:/text.txt"); 18 19 }catch(FileNotFoundException e) { 20 e.printStackTrace(); 21 } 22 int sum=0; 23 24 for(int i=0;i<10;i++) 25 { 26 int a=new Random().nextInt(100); 27 int b=new Random().nextInt(100); 28 Scanner in=new Scanner(System.in); 29 //in.close(); 30 31 switch((int)(Math.random()*4)) 32 33 { 34 35 case 0: 36 System.out.println( ""+a+"+"+b+"="); 37 38 int M = in.nextInt(); 39 out.println(a+"+"+b+"="+M); 40 if (M == counter.add(a, b)) { 41 sum += 10; 42 System.out.println("答案正确"); 43 } 44 else { 45 System.out.println("答案错误"); 46 } 47 48 break ; 49 case 1: 50 if(a<b) 51 { 52 int temp=a; 53 a=b; 54 b=temp; 55 }//为避免减数比被减数大的情况 56 57 System.out.println(""+a+"-"+b+"="); 58 /*while((a-b)<0) 59 { 60 b = (int) Math.round(Math.random() * 100); 61 62 }*/ 63 int N= in.nextInt(); 64 65 out.println(a+"-"+b+"="+N); 66 if (N == counter.reduce(a, b)) { 67 sum += 10; 68 System.out.println("答案正确"); 69 } 70 else { 71 System.out.println("答案错误"); 72 } 73 74 break ; 75 76 77 78 79 case 2: 80 81 System.out.println(""+a+"*"+b+"="); 82 int c = in.nextInt(); 83 out.println(a+"*"+b+"="+c); 84 if (c == counter.multiply(a, b)) { 85 sum += 10; 86 System.out.println("答案正确"); 87 } 88 else { 89 System.out.println("答案错误"); 90 } 91 break; 92 case 3: 93 94 95 System.out.println(""+a+"/"+b+"="); 96 while(b==0) 97 { b = (int) Math.round(Math.random() * 100); 98 } 99 int c0= in.nextInt(); 100 out.println(a+"/"+b+"="+c0); 101 if (c0 == counter.devision(a, b)) { 102 sum += 10; 103 System.out.println("答案正确"); 104 } 105 else { 106 System.out.println("答案错误"); 107 } 108 109 break; 110 111 112 } 113 } 114 System.out.println("totlescore:"+sum); 115 out.println(sum); 116 117 out.close(); 118 } 119 }
1 package MM; 2 3 public class MNM{ 4 public int add(int a,int b) 5 { 6 return a+b; 7 } 8 public int reduce(int a,int b) 9 { 10 if((a-b)>0) 11 return a-b; 12 else return 0; 13 } 14 public int multiply(int a,int b) 15 { 16 return a*b; 17 } 18 public int devision(int a,int b) 19 { 20 if(b!=0) 21 return a/b; 22 else return 0; 23 24 } 25 }
程序总体结构:Demo类实现MNM类的功能。
模块说明:随机生成100以内的加减乘除四则运算,输入答案,程序检查答案是否正确。
目前程序设计存在的困难与问题:对于除法运算还存在输出一些问题。
编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。
1 package MM; 2 3 import java.util.Random; 4 import java.util.Scanner; 5 6 import java.io.FileNotFoundException; 7 8 import java.io.PrintWriter; 9 10 public class Demo{ 11 public static void main(String[] args) 12 { 13 14 MNM counter=new MNM();//与其它类建立联系 15 PrintWriter out=null; 16 try { 17 out=new PrintWriter("D:/text.txt"); 18 19 }catch(FileNotFoundException e) 20 { 21 e.printStackTrace(); 22 } 23 int sum=0; 24 25 for(int i=0;i<10;i++) 26 { 27 int a=new Random().nextInt(100); 28 int b=new Random().nextInt(100); 29 Scanner in=new Scanner(System.in); 30 //in.close(); 31 32 switch((int)(Math.random()*4)) 33 34 { 35 36 case 0: 37 System.out.println( ""+a+"+"+b+"="); 38 39 int M = in.nextInt(); 40 System.out.println(a+"+"+b+"="+M); 41 if (M == counter.add(a, b)) { 42 sum += 10; 43 System.out.println("答案正确"); 44 } 45 else { 46 System.out.println("答案错误"); 47 } 48 49 break ; 50 case 1: 51 if(a<b) 52 { 53 int temp=a; 54 a=b; 55 b=temp; 56 }//为避免减数比被减数大的情况 57 58 System.out.println(""+a+"-"+b+"="); 59 /*while((a-b)<0) 60 { 61 b = (int) Math.round(Math.random() * 100); 62 63 }*/ 64 int N= in.nextInt(); 65 66 System.out.println(a+"-"+b+"="+N); 67 if (N == counter.reduce(a, b)) 68 { 69 sum += 10; 70 System.out.println("答案正确"); 71 } 72 else { 73 System.out.println("答案错误"); 74 } 75 76 break ; 77 78 79 case 2: 80 System.out.println(""+a+"*"+b+"="); 81 int c = in.nextInt(); 82 System.out.println(a+"*"+b+"="+c); 83 if (c == counter.multiply(a, b)) { 84 sum += 10; 85 System.out.println("答案正确"); 86 } 87 else { 88 System.out.println("答案错误"); 89 } 90 break; 91 case 3: 92 93 while(b==0) 94 { b = (int) Math.round(Math.random() * 100);//满足分母不为0 95 } 96 while(a%b!=0) 97 { 98 a = (int) Math.round(Math.random() * 100); 99 b = (int) Math.round(Math.random() * 100); 100 } 101 System.out.println(""+a+"/"+b+"="); 102 while(b==0) 103 { b = (int) Math.round(Math.random() * 100); 104 } 105 int c0= in.nextInt(); 106 System.out.println(a+"/"+b+"="+c0); 107 if (c0 == counter.devision(a, b)) { 108 sum += 10; 109 System.out.println("答案正确"); 110 } 111 else { 112 System.out.println("答案错误"); 113 } 114 115 break; 116 117 118 } 119 } 120 System.out.println("totlescore:"+sum); 121 System.out.println(sum); 122 123 out.close(); 124 } 125 }
1 package MM; 2 3 public class MNM <T>{ 4 private T a; 5 private T b; 6 public void MNM() 7 { 8 a=null; 9 b=null; 10 } 11 public MNM(T a,T b) 12 { 13 this.a=a; 14 this.b=b; 15 } 16 public MNM() { 17 // TODO 自动生成的构造函数存根 18 } 19 public int add(int a,int b) 20 { 21 return a+b; 22 } 23 public int reduce(int a,int b) 24 { 25 if((a-b)>0) 26 return a-b; 27 else return 0; 28 } 29 public int multiply(int a,int b) 30 { 31 return a*b; 32 } 33 public int devision(int a,int b) 34 { 35 if(b!=0&&a%b==0) 36 return a/b; 37 else 38 return 0; 39 40 } 41 }
程序运行结果如下:
实验总结:
在这一周的学习中我们主要学习的是泛型程序设计,泛型接口的定义,泛型变量的限定以及通配符类型及使用方法,然后这周的编程练习主要是对之前的程序进行改进,通过编程练习将这周学过泛型程序设计运用到程序中。