王海珍 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 }
測試結果如下所示
第三部分 實驗總結
本章節主要學習了泛型程式設計,泛型程式設計意味著編寫程式碼可以被很多不同型別的物件所重用。而本章節的內容對我自己來說學起來還是存在許多問題的,所以下去還的多練多看書,尤其是關於本章節的泛型的使用等各個方面。