一:理論部分java
1.泛型:也稱參數化類型(parameterized type),就是在定義類、接口和方法時,經過類型參數指示將要處理的對象類型。(如ArrayList類)。編程
2.泛型程序設計(Generic programming):編寫代碼能夠被不少不一樣類型的對象所重用。dom
3.Pair類引入了一個類型變量T,用尖括號(<>)括起來,並放在類名的後面。ide
4.泛型類能夠有多個類型變量。例如:學習
public class Pair<T, U> { … }測試
5.類定義中的類型變量用於指定方法的返回類型以及域、局部變量的類型。this
6.泛型方法的聲明:泛型方法(1)除了泛型類外,還能夠只單獨定義一個方法做爲泛型方法,用於指定方法參數或者返回值爲泛型類型,留待方法調用時肯定。spa
(2)泛型方法能夠聲明在泛型類中,也能夠聲明在普通類中。設計
7.泛型接口的定義:3d
public interface IPool <T>
{
T get();
int add(T t);
}
8.泛型變量的限定:(1)定義泛型變量的上界:public class NumberGeneric< T extends Number>
上述聲明規定了NumberGeneric類所能處理的泛型變量類型,需和Number有繼承關係。
extends關鍵字所聲明的上界既能夠是一個類,也能夠是一個接口。
(2)定義泛型變量的下界:List<? super CashCard> cards = new ArrayList<T>();
下界說明:經過super關鍵字能夠固定泛型參數的類型爲某種類型或者其超類。
檔程序但願爲一個方法的參數限定時,一般能夠使用下限通配符。
9.通配符類型:「?」符號標明參數的類型能夠是任何一種類型,他和參數T的含義是有區別的,T表示一種未知類型,而?標明任何一種類型。
這種通配符通常有如下三種用法:(1)單獨的?:用於表示任何類型。
(2)?extends type:表示帶有上界
(3)?super type:表示帶有下界
10.pair與pair<?>de區別在於:能夠用任意object對象調用原始的pair類的setobject方法。
二:實驗部分:
實驗十 泛型程序設計技術
實驗時間 2018-11-1
1、實驗目的與要求
(1) 理解泛型概念;
(2) 掌握泛型類的定義與使用;
(3) 掌握泛型方法的聲明與使用;
(4) 掌握泛型接口的定義與實現;
(5)瞭解泛型程序設計,理解其用途。
2、實驗內容和步驟
實驗1: 導入第8章示例程序,測試程序並進行代碼註釋。(如下三個測試程序中的pair類都相同,只需將三個程序定義在同一個包中,便可共用)
測試程序1:(在如下測試程序中,再也不贅述主類pair類)
l 編輯、調試、運行教材3十一、312頁 代碼,結合程序運行結果理解程序;
l 在泛型類定義及使用代碼處添加註釋;
l 掌握泛型類的定義及使用。
package pair1; /** * @version 1.00 2004-05-10 * @author Cay Horstmann */ public class Pair<T>//一個pair泛型類,引入一個類型變量T,該類能夠有多個類型變量。 { private T first;//類型變量T指定方法的返回類型以及域和局部變量的類型。 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" };//默認比較ASCII碼值 Pair<String> mm = ArrayAlg.minmax(words);//用具體類型替換類型變量T,便可實例化泛型類型。 //經過類名調用方法,該方法爲靜態的。 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)//stringPair類對象 { 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; import java.time.*;//比較日期的大小調用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);//用LocateDate實例化泛型類型 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) //爲確信有compareTo方法,將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.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<>();//也可用Mannager,由於Employee類是他的父類,在此可直接用它的父類Employee 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類 { 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); // OK--swapHelper captures wildcard type } // Can't write public static <T super manager> ... } class PairAlg { public static boolean hasNulls(Pair<?> p)//pair<?>,表示能夠用任何Object對象調用原始的pair類的setobject方法。 { 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//mannager做爲一個子類繼承自它的父類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);//super調用超類中的一些方法 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//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; } }
實驗2:編程練習:
編程練習1:實驗九編程題總結
l 實驗九編程練習1總結(從程序整體結構說明、模塊說明,目前程序設計存在的困難與問題三個方面闡述)。
總結:(1)該程序有兩個類構成,一個主類,
package text8; 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.List; import java.util.Scanner; public class Xinxi { private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\\身份證號\\身份證號.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) {//添加的異常處理語句try{ }catch{ }語句 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 n = scanner.next(); switch (n) { 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, flag = 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; flag = i; } } return flag; } }
一個student類,該類實現了一個接口。
package text8; public class Student implements Comparable<Student> { private String name; private String number; private String sex; private String province; private int age; public void setName(String name) { // TODO 自動生成的方法存根 this.name = name; } public String getName() { // TODO 自動生成的方法存根 return name; } public void setnumber(String number) { // TODO 自動生成的方法存根 this.number = number; } public String getNumber() { // TODO 自動生成的方法存根 return number; } public void setsex(String sex) { // TODO 自動生成的方法存根 this.sex = sex; } public String getsex() { // TODO 自動生成的方法存根 return sex; } public void setprovince(String province) { // TODO 自動生成的方法存根 this.province = province; } public String getprovince() { // TODO 自動生成的方法存根 return province; } public void setage(int a) { // TODO 自動生成的方法存根 this.age = age; } public int getage() { // TODO 自動生成的方法存根 return age; } public int compareTo(Student o) { return this.name.compareTo(o.getName()); } public String toString() { return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n"; } }
(2)在該程序中添加異常處理語句。採用積極拋出異常的模式,處理程序中可能會出現的異常。
(3)目前程序設計存在的困難是,能夠將一個模塊一個模塊的寫出來,但不知道該怎麼將這些模塊組織起來成一個完整的程序。
還有在程序運行結果出現一些不應出現的符號時,不知道該如何準確的修改。
l 實驗九編程練習2結(從程序整體結構說明、模塊說明,目前程序設計存在的困難與問題三個方面闡述)。
總結:(1)該程序有兩個類構成,一個主類,
package 第九周; import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Demo { public static void main(String[] args) { // 用戶的答案要從鍵盤輸入,所以須要一個鍵盤輸入流 //Scanner in = new Scanner(System.in); yunsuan counter = new yunsuan (); PrintWriter out = null; try { out = new PrintWriter("D:\\text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int sum = 0; // 經過循環生成10道題 for (int i = 0; i < 10; i++) { int a = (int) Math.round(Math.random() * 10); int b = (int) Math.round(Math.random() * 10); Scanner in1 =new Scanner(System.in); switch((int)(Math.random()*4)) { case 1: System.out.println( ""+a+"+"+b+"="); int c1 = in1.nextInt(); out.println(a+"+"+b+"="+c1); if (c1 == counter.add(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break ; case 2: System.out.println(i + ": " + a + "-" + b + "="); int c2 = in1.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == counter.reduce(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break; case 3: System.out.println(i + ": " + a + "*" + b + "="); int c3 = in1.nextInt(); out.println(a + "*" + b + "=" + c3); if (c3 == counter.multiplication(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break; case 4: System.out.println(""+a+"/"+b+"="); while(b==0) { b = (int) Math.round(Math.random() * 100); } int c4= in1.nextInt(); out.println(a+"/"+b+"="+c4); if (c4 == counter.devision(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break; } } System.out.println("總分:"+sum); out.println(sum); out.close(); } }
一個用戶自定義類
package 第九周; public class yunsuan { public int multiplication(int a, int b) { // TODO 自動生成的方法存根 return a*b; } public int add(int a, int b) { // TODO 自動生成的方法存根 return a+b; } public int reduce(int a, int b) { // TODO 自動生成的方法存根 if((a-b)>0) return a-b; else return 0; } public int devision(int a, int b) { // TODO 自動生成的方法存根 if(b!=0) return a/b; else return 0; } }
(2)存在的困難是,有些運算超出小學生的計算範圍,當回答正確時,會生成10道四則運算習題,當有一個回答不正確時,生成的四則運算習題不是十道。
將生成的十道四則運算題目保存在txt文檔中。
編程練習2:採用泛型程序設計技術改進實驗九編程練習2,使之可處理實數四則運算,其餘要求不變。
package 第九周; import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Demo { public static void main(String[] args) { // 用戶的答案要從鍵盤輸入,所以須要一個鍵盤輸入流 Scanner in = new Scanner(System.in); yunsuan counter = new yunsuan (); PrintWriter out = null; try { out = new PrintWriter("D:\\text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int sum = 0; // 經過循環生成10道題 for (int i = 0; i < 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); //Scanner in1 =new Scanner(System.in); Random rand=new Random(); switch((int)(Math.random()*4)+1) { case 1: System.out.println( ""+a+"+"+b+"="); int c= in.nextInt(); out.println(a+"+"+b+"="+c); if (c == counter.add(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break ; case 2: while (a<b) { b = (int)Math.round(Math.random() * 100); ; } System.out.println(i + ": " + a + "-" + b + "="); int c1 = in.nextInt(); out.println(a + "-" + b + "=" + c1); if (c1 == counter.reduce(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break; case 3: System.out.println(i + ": " + a + "*" + b + "="); int c2 = in.nextInt(); out.println(a + "*" + b + "=" + c2); if (c2 == counter.multiplication(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break; case 4: 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(""+a+"/"+b+"="); int c3= in.nextInt(); out.println(a+"/"+b+"="+c3); if (c3 == counter.devision(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉答案錯誤"); } break; } } System.out.println("總分:"+sum); out.println(sum); out.close(); } }
package 第九周; public class yunsuan<T>{ private T a; private T b; public yunsuan() { a=null; b=null; } public int multiplication(int a, int b) { // TODO 自動生成的方法存根 return a*b; } public int add(int a, int b) { // TODO 自動生成的方法存根 return a+b; } public int reduce(int a, int b) { // TODO 自動生成的方法存根 if((a-b)>0)//保證兩數相減不會是負數 return a-b; else return 0; } public int devision(int a, int b) { // TODO 自動生成的方法存根 if (b != 0 && a%b==0)//保證是整除 return a/b; else return 0; } }
三:實驗總結:經過本週的學習,掌握了泛型類的定義,以及泛型方法的聲明,還有泛型接口的定義,以及對泛型變量的限定。
但在用泛型類寫程序時仍是有一點點的困難。在學長的指導幫助下學會了如何閱讀別人的程序,並用快捷方法進入某一個類去讀它的定義。