徐思201771010132《面向對象程序設計(java)》第十周學習總結
一、理論知識部分
泛型:也稱參數化類型,就是在定義類、接口和方法時,通過類型參數指示將要處理的對象類型。(如ArrayList類)
泛型程序設計(Generic programming):編寫代碼可以被很多不同類型的對象所重用。
一個泛型類(generic class)就是具有一個或多個類型變量的類,即創建用類型作為參數的類。如一個泛型類定義格式如下: class Generics<K,V>其中的K和V是類中的可變類型參數。
泛型類可以有多個類型變量。例如: public class Pair<t, u=""> <T,U>{ … }
類定義中的類型變量用於指定方法的返回類型以及域、局部變量的類型。
泛型方法:除了泛型類外,還可以只單獨定義一個方法作為泛型方法,用於指定方法參數或者返回值為泛型類型,留待方法調用時確定。泛型方法可以聲明在泛型類中,也可以聲明在 普通類中。
extends關鍵字所聲明的上界既可以是一個類,也可以是一個接口
<T extends Bounding Type>表示T應該是綁定類型的子類型。一個類型變量或通配符可以有多個限定,限定類型用“&”分割。
泛型變量下界:通過使用super關鍵字可以固定泛型參數的類型為某種類型或者其超類。當程序希望為一個方法的參數限定類型時,通常可以使用下限通配符
通配符:“?”符號表明參數的類型可以是任何一種類型,它和參數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 classPair<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.LocalDate; /** * @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) //通過對類型變量T設置限定,將T限制為實現了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; /** * @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; 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.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總結(從程序總體結構說明、模塊說明,目前程序設計存在的困難與問題三個方面闡述)。
總體結構:主類Main 子類Person
模塊說明:Main:查找文件,對文件進行讀取。
Person:對文件進行具體的處理
package ID; 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) { 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" + birthplace + "\n"; } }
package ID; 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 Main { private static ArrayList<Person> Personlist; public static void main(String[] args) { Personlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("身份證號.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 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); Personlist.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:按省份找同鄉"); System.out.println("4:輸入你的年齡,查詢年齡與你最近人的信息"); System.out.println("5:退出"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort(Personlist); System.out.println(Personlist.toString()); break; case 2: int max = 0, min = 100; int j, k1 = 0, k2 = 0; for (int i = 1; i < Personlist.size(); i++) { j = Personlist.get(i).getage(); if (j > max) { max = j; k1 = i; } if (j < min) { min = j; k2 = i; } } System.out.println("年齡最大:" + Personlist.get(k1)); System.out.println("年齡最小:" + Personlist.get(k2)); break; case 3: System.out.println("省份?"); String find = scanner.next(); String place = find.substring(0, 3); String place2 = find.substring(0, 3); for (int i = 0; i < Personlist.size(); i++) { if (Personlist.get(i).getbirthplace().substring(1, 4).equals(place)) System.out.println("同鄉 " + Personlist.get(i)); } break; case 4: System.out.println("年齡:"); int yourage = scanner.nextInt(); int near = agenear(yourage); int d_value = yourage - Personlist.get(near).getage(); System.out.println("" + Personlist.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, d_value = 0, k = 0; for (int i = 0; i < Personlist.size(); i++) { d_value = Personlist.get(i).getage() - age; if (d_value < 0) d_value = -d_value; if (d_value < min) { min = d_value; k = i; } } return k; } }
問題:查找不到文件,代碼編程不是太會
l 實驗九編程練習2總結(從程序總體結構說明、模塊說明,目前程序設計存在的困難與問題三個方面闡述)。
總體結構:主類:Main 子類:math
模塊說明:Main:隨機生成十道100內的計算題,並判斷答案正誤
math:對具體計算進行處理
public class math { private int a; private int b; public static int add(int a, int b) { return a + b; } public static int reduce(int a, int b) { return a - b; } public static int multiplication(int a, int b) { return a * b; } public static int division(int a, int b) { if (b != 0) return a / b; else return 0; } }
import java.io.*; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); 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() * 4); switch (m) { case 1: System.out.println(i + ": " + a + "/" + b + "="); while (b == 0) { b = (int) Math.round(Math.random() * 100); } int c1 = in.nextInt(); if (c1 == a / b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; case 2: System.out.println(i + ": " + a + "*" + b + "="); int c2 = in.nextInt(); if (c2 == a * b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; case 3: System.out.println(i + ": " + a + "+" + b + "="); int c3 = in.nextInt(); if (c3 == a + b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; case 4: System.out.println(i + ": " + a + "-" + b + "="); int c4 = in.nextInt(); if (c4 == a - b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; } } System.out.println("成績" + sum); } }
問題:不符合小學四則運算要求,有的計算結果出現了負數
編程練習2:采用泛型程序設計技術改進實驗九編程練習2,使之可處理實數四則運算,其他要求不變。
import java.io.*; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter output = null; try { output = 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() * 4); switch (m) { case 1: 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 c1 = in.nextInt(); output.println(a + "/" + b + "=" + c1); if (c1 == a / b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; case 2: System.out.println(i + ": " + a + "*" + b + "="); int c2 = in.nextInt(); output.println(a + "*" + b + "=" + c2); if (c2 == a * b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; case 3: System.out.println(i + ": " + a + "+" + b + "="); int c3 = in.nextInt(); output.println(a + "+" + b + "=" + c3); if (c3 == a + b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; case 4: while (a < b) { a = (int) Math.round(Math.random() * 100); } System.out.println(i + ": " + a + "-" + b + "="); int c4 = in.nextInt(); output.println(a + "-" + b + "=" + c4); if (c4 == a - b) { System.out.println("恭喜答案正確"); sum += 10; } else { System.out.println("抱歉,答案錯誤"); } break; } } System.out.println("成績" + sum); output.println("成績" + sum); output.close(); } }
public class math<T> { private T a; private T 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; } }
三:實驗總結:
通過這次實驗,我了解了泛型類,泛型方法、通配符、泛型變量上界、泛型變量下界。通過對之前實驗的總結,對之前的知識進行進一步的回顧,通過改進代碼更好的了解了泛型程序設計。編程仍需多加練習,對之前的知識需要多加復習鞏固。
徐思201771010132《面向對象程序設計(java)》第十周學習總結