王豔 201771010127《面向物件程式設計(java)》第十週學習總結
一:理論部分。
1.泛型程式設計意味著編寫的程式碼可以被很多不同型別的物件所重用。
1)泛型(引數化型別):在定義類、介面和方法時,通過型別引數指示將要處理的物件型別。如ArrayList類是一個泛型程式設計的例項,可以聚集任何型別的物件。
2)泛型類:就是具有一個或多個型別變數的類,即建立用型別作為引數的類。在<>內定義形式型別引數,該形參表示型別而不表示值。
泛型類可以有多個型別變數,例如:public class Pair<T, U>
類定義中的型別變數用於指定方法的返回型別以及域、區域性變數的型別。
3)泛型方法:除了泛型類外,還可以只單獨定義一個方法作為泛型方法,用於指定方法引數或者返回值為泛型型別,在方法呼叫時確定具體需要。(泛型方法可以宣告在泛型類中,也可以宣告在普通類中)
4)泛型變數的限定:a.泛型變數的上界:如<T extends Number>(extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面,extends並不代表繼承,它是類型範圍限制。)
b.泛型變數的上界:如<? super CashCard>(通過使用super關鍵字可以固定泛型引數的型別為某種型別或者其超類當程式希望為一個方法的引數限定型別時,通常可以使用下限萬用字元)
2.泛型類的約束與侷限性。
1)不能用基本型別(如int型,float型等)例項化型別引數
2)執行時型別查詢只適用於原始型別
3)不能丟擲也不能捕獲泛型類例項
4)引數化型別的陣列不合法
5)不能例項化型別變數
6)泛型類的靜態上下文中型別變數無效
7)注意擦除後的衝突
3.泛型型別的繼承規則:Java中的陣列是協變的,但這一原理不適用於泛型型別。
泛型類可擴充套件或實現其它的泛型類。
4.萬用字元:“?”符號表明引數的型別可以是任何一種型別,而T表示一種未知型別。
萬用字元的一般用法:a.?:用於表示任何型別;
b.? extends type,表示帶有上界;
c.? super type,表示帶有下界。
二:實驗部分。
1、實驗目的與要求
(1) 理解泛型概念;
(2) 掌握泛型類的定義與使用;
(3) 掌握泛型方法的宣告與使用;
(4) 掌握泛型介面的定義與實現;
(5)瞭解泛型程式設計,理解其用途。
2、實驗內容和步驟
實驗1: 匯入第8章示例程式,測試程式並進行程式碼註釋。
測試程式1:
l 編輯、除錯、執行教材311、312頁 程式碼,結合程式執行結果理解程式;
l 在泛型類定義及使用程式碼處添加註釋;
l 掌握泛型類的定義及使用。
程式如下:
/** * @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);//一對字串:min,max 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++)//length:陣列屬性值 { if (min.compareTo(a[i]) > 0) min = a[i]; if (max.compareTo(a[i]) < 0) max = a[i]; }//實現字串比較大小 return new Pair<>(min, max); } }
/** * @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 掌握泛型方法、泛型變數限定的定義及用途。
程式如下:
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) //泛型方法(comparable是T的上界約束) { if (a == null || a.length == 0) return null; T min = a[0]; T max = a[0];//min和max與T的型別一致 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); } }
/** * @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,結合程式執行結果理解程式;
l 瞭解萬用字元型別的定義及用途。
程式如下:
/** * @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)//萬用字元型別(帶有上界)extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面。 { 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)//萬用字元型別(帶有下界) { minmaxBonus(a, result); PairAlg.swapHelper(result); //swapHelper捕獲萬用字元型別 } //無法編寫公共靜態< T超級管理器> } class PairAlg { public static boolean hasNulls(Pair<?> p)//通過將hasNulls轉換成泛型方法,避免使用萬用字元型別 { return p.getFirst() == null || p.getSecond() == null; } public static void swap(Pair<?> p) { swapHelper(p); } public static <T> void swapHelper(Pair<T> p)//使用輔助方法swapHelper(泛型方法),以在交換時臨時儲存第一個元素 { T t = p.getFirst(); p.setFirst(p.getSecond()); p.setSecond(t); } }
/** * @version 1.00 2004-05-10 * @author Cay Horstmann */ public class Pair<T> { private T first; private T second; //T是未知型別,不代表值 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; } }
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; } }
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; } }
程式執行結果如下:
實驗2:程式設計練習:
程式設計練習1:實驗九程式設計題總結
l 實驗九程式設計練習1總結(從程式總體結構說明、模組說明,目前程式設計存在的困難與問題三個方面闡述)。
程式總體結構:定義了一個主類Test,一個介面。
模組:
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 Test{ private static ArrayList<Person> Personlist1; public static void main(String[] args) { Personlist1 = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("C:\\Users\\lenovo\\Documents\\身份證"); try { FileInputStream F = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(F)); 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 place =linescanner.nextLine(); Person Person = new Person(); Person.setname(name); Person.setid(id); Person.setsex(sex); int a = Integer.parseInt(age); Person.setage(a); Person.setbirthplace(place); Personlist1.add(Person); } } 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.輸入你的年齡,查詢身份證號.txt中年齡與你最近人的姓名、身份證號、年齡、性別和出生地"); System.out.println("4:按省份找你的同鄉;"); System.out.println("5:退出"); int type = scanner.nextInt(); switch (type) { case 1: Collections.sort(Personlist1); System.out.println(Personlist1.toString()); break; case 2: int max=0,min=100;int j,k1 = 0,k2=0; for(int i=1;i<Personlist1.size();i++) { j=Personlist1.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年齡最大:"+Personlist1.get(k1)); System.out.println("年齡最小:"+Personlist1.get(k2)); break; case 3: System.out.println("place?"); String find = scanner.next(); String place=find.substring(0,3); String place2=find.substring(0,3); for (int i = 0; i <Personlist1.size(); i++) { if(Personlist1.get(i).getbirthplace().substring(1,4).equals(place)) { System.out.println("你的同鄉:"+Personlist1.get(i)); } } break; case 4: System.out.println("年齡:"); int yourage = scanner.nextInt(); int close=ageclose(yourage); int d_value=yourage-Personlist1.get(close).getage(); System.out.println(""+Personlist1.get(close)); break; case 5: isTrue = false; System.out.println("再見!"); break; default: System.out.println("輸入有誤"); } } } public static int ageclose(int age) { int m=0; int max=53; int d_value=0; int k=0; for (int i = 0; i < Personlist1.size(); i++) { d_value=Personlist1.get(i).getage()-age; if(d_value<0) d_value=-d_value; if (d_value<max) { max=d_value; k=i; } } return k; } }
public class Person implements Comparable<Person> { private String name; private String id; private int age; private String sex; 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 int getage() { return age; } public void setage(int age) { // int a = Integer.parseInt(age); this.age= age; } public String getsex() { return sex; } public void setsex(String sex) { this.sex= sex; } public String getbirthplace() { return birthplace; } public void setbirthplace(String birthplace) { this.birthplace= birthplace; } public int compareTo(Person o) { return this.name.compareTo(o.getname()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+id+"\t"; } }
目前程式設計存在的困難與問題:
1)對一些知識理解不到位,不能很好地將理論知識應用到程式編寫中。
2)當程式中處出現異常時,處理方式最多隻能應用丟擲異常這種消極方式。
3)分不清如何使用字元流和位元組流。
l 實驗九程式設計練習2總結(從程式總體結構說明、模組說明,目前程式設計存在的困難與問題三個方面闡述)。
程式總體結構:一個主類Demo,一個使用者自定義類Number
模組:
import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; public class Demo { public static void main(String[] args) { Scanner in = new Scanner(System.in); Number counter = new Number(); PrintWriter out = null; try { out = new PrintWriter("text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block 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 = (int) Math.round(Math.random() * 3); Random n = new Random(); switch (m) { case 0: System.out.println(i + ": " + a + "/" + b + "="); while (b == 0) { b = (int) Math.round(Math.random() * 100); } int c = in.nextInt(); out.println(a + "/" + b + "=" + c); if (c == counter.division(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 1: System.out.println(i + ": " + a + "*" + b + "="); int c1 = in.nextInt(); out.println(a + "*" + b + "=" + c1); if (c1 == counter.multiplication(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 2: System.out.println(i + ": " + a + "+" + b + "="); int c2 = in.nextInt(); out.println(a + "+" + b + "=" + c2); if (c2 == counter.add(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 3: System.out.println(i + ": " + a + "-" + b + "="); int c3 = in.nextInt(); out.println(a + "-" + b + "=" + c3); if (c3 == counter.reduce(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; } } System.out.println("成績" + sum); out.println("成績:" + sum); out.close(); } }
public class Number { private int a; private int b; public int add(int a, int b) { return a + b; } public int reduce(int a, int b) { 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; } }
目前程式設計存在的困難與問題:
1)沒有考慮到除法運算中運算結果為小數小數以及除數為0的情況。
2)找不到檔案儲存路徑,只能通過電腦搜尋獲得,對檔案的理解還不到位。
3)對異常的除錯還存在很大的問題。
程式設計練習2:採用泛型程式設計技術改進實驗九程式設計練習2,使之可處理實數四則運算,其他要求不變。
程式如下:
package Demo; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner in = new Scanner(System.in); Number counter = new Number(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); } catch (FileNotFoundException e) { System.out.println("Error!"); 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; 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); } //a大於b,a%b為0(保證能整除) System.out.println(i + ": " + a + "/" + b + "="); int c0 = in.nextInt(); out.println(a + "/" + b + "=" + c0); if (c0 == counter.division(a, b)) { sum += 10; System.out.println("恭喜答案正確!"); } else { System.out.println("抱歉答案錯誤!"); } break; case 2: System.out.println(i + ": " + a + "*" + b + "="); int c = in.nextInt(); out.println(a + "*" + b + "=" + c); if (c == counter.multiplication(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 == counter.add(a, b)) { sum += 10; System.out.println("恭喜答案正確!"); } else { System.out.println("抱歉答案錯誤!"); } break; case 4: while (a < b) { b = (int) Math.round(Math.random() * 100); } //若a<b,則重新生成b(避免出現負數) System.out.println(i + ": " + a + "-" + b + "="); int c2 = in.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == counter.reduce(a, b)) { sum += 10; System.out.println("恭喜答案正確!"); } else { System.out.println("抱歉答案錯誤!"); } break; } } System.out.println("成績" + sum); out.println("成績:" + sum); out.close(); } }
package Demo; public class Number<T> { private T a; private T b; public Number() { a = null; b = null; } public Number(T a, T b) { this.a = a; this.b = b; } public int add(int a,int b) { return a + b; } public int reduce(int a, int b) { return a - b; } public int multiplication(int a, int b) { return a * b; } public int division(int a, int b) { if (b != 0 && a%b==0) return a / b; else return 0; } }
程式執行結果如下:
三:實驗總結。
這周主要學習了泛型程式,泛型類和泛型方法同時具備可重用性、型別安全和效率,泛型類不會強行對值型別進行裝箱和拆箱,或對引用型別進行向下強制型別轉換,所以是程式設計效能得到提高。在學習理論課時,聽老師講泛型類不算特別難,但在實驗課上執行程式時,並不是太理解程式,經過老師和學長的講解,對程式有了一定程度的理解,但是也只是基本能讀懂程式,在自己程式設計時,還是有很大問題。在之後的學習中,我會多練習程式去了解這些知識,爭取能夠獨立完整的編寫程式。