實驗十 泛型程序設計技術java
實驗時間 2018-11-1編程
基礎知識:數組
1 什麼是泛型程序設計?
. JDK 5.0 中增長的泛型類型,是Java 語言中類型安全的一次重要改進。
. 泛型:也稱參數化類型(parameterized type),就是在定義類、接口和方法時,經過類型參數指示將要處理的對象類型。(如ArrayList類)
. 泛型程序設計(Generic programming):編寫代碼能夠被不少不一樣類型的對象所重用。安全
2 泛型類的定義 :一個泛型類(generic class)就是具備一個或多個類型變量的類,即建立用類型做爲參數的類。如一個泛型類定義格式以下:
class Generics<K,V>其中的K和V是類中的可變類型參數。
Pair類引入了一個類型變量T,用尖括號(<>)括起來,並放在類名的後面。泛型類能夠有多個類型變量。例如:
public class Pair<T, U> { … }類定義中的類型變量用於指定方法的返回類型以及域、局部變量的類型。dom
3 泛型方法的聲明: 除了泛型類外,還能夠只單獨定義一個方法做爲泛型方法,用於指定方法參數或者返回值爲泛型類型,留待方法調用時肯定。
– 泛型方法能夠聲明在泛型類中,也能夠聲明在普通類中。ide
4 泛型變量的限定:public class NumberGeneric< T extends Number>泛型變量上界的說明,上述聲明規定了NumberGeneric類所能處理的泛型變量類型需和Number有繼承關係;extends關鍵字所聲明的上界既能夠是一個類,也能夠是一個接口;學習
List<? super CashCard> cards = new ArrayList<T>();泛型變量下界的說明,經過使用super關鍵字能夠固定泛型參數的類型爲某種類型或者其超類, 當程序但願爲一個方法的參數限定類型時,一般能夠使用下限通配符。測試
5 泛型類的約束與侷限性(*)
不能用基本類型實例化類型參數
運行時類型查詢只適用於原始類型
不能拋出也不能捕獲泛型類實例
參數化類型的數組不合法
不能實例化類型變量
泛型類的靜態上下文中類型變量無效
注意擦除後的衝突this
6 通配符類型通配符: 「?」符號代表參數的類型能夠是任何一種類型,它和參數T的含義是有區別的。T表示一種未知類型,而「?」表示任何一種類型。這種通配符通常有如下三種用法:
– 單獨的?,用於表示任何類型。
– ? extends type,表示帶有上界。
– ? super type,表示帶有下界。spa
實驗內容
1、實驗目的與要求
(1) 理解泛型概念;
(2) 掌握泛型類的定義與使用;
(3) 掌握泛型方法的聲明與使用;
(4) 掌握泛型接口的定義與實現;
(5)瞭解泛型程序設計,理解其用途。
2、實驗內容和步驟
實驗1: 導入第8章示例程序,測試程序並進行代碼註釋。
測試程序1:
l 編輯、調試、運行教材3十一、312頁 代碼,結合程序運行結果理解程序;
l 在泛型類定義及使用代碼處添加註釋;
l 掌握泛型類的定義及使用。
package pair1; /** * @version 1.00 2004-05-10 * @author Cay Horstmann */ //Pair泛型類 public class Pair<T> //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];//若比較結果大於0,則代表此時的min不是最小的,將新的字符串存進min if (max.compareTo(a[i]) < 0) max = a[i];//和上面min的 比較方法同樣 } return new Pair<>(min, max);//返回新的Pair類對象 } }
測試程序2:
l 編輯、調試運行教材315頁 PairTest2,結合程序運行結果理解程序;
l 在泛型程序設計代碼處添加相關注釋;
l 掌握泛型方法、泛型變量限定的定義及用途。
package pair1; /** * @version 1.00 2004-05-10 * @author Cay Horstmann */ //Pair泛型類 public class Pair<T> //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);//定義Pair類對象mm 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限制爲 實現了Comparable接口的類,則泛型的minmax方法只能被實現了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];//若比較結果大於0,則代表此時的min不是最小的,將新的字符串存進min if (max.compareTo(a[i]) < 0) max = a[i];//和上面min的 比較方法同樣 } return new Pair<>(min, max);//返回新的Pair類對象 } }
測試程序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//子類爲manager,父類爲emploee { 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> //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的任何一種類型 { 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)//?是通配符,代表參數的類型是下界爲manager的任何一種類型 { 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.程序整體結構說明:
主類爲xinxi,子類爲Student
2.模塊說明:
首先是文件的讀入操做,而後利用switch語句對須要處理的幾種狀況進行了分別處理。
package xinxi; 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 xinxi{ private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); File file = new File("F:\\身份證號.txt"); try { FileInputStream fis = new FileInputStream(file); @SuppressWarnings("resource") BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { @SuppressWarnings("resource") 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) { 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.查找你的同鄉"); 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("年齡:"); int yourage = scanner.nextInt(); int near=agenear(yourage); @SuppressWarnings("unused") int value=yourage-studentlist.get(near).getage(); System.out.println("和你年齡相近的是"+studentlist.get(near)); break; case "4": 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; } } } public static int agenear(int age) { @SuppressWarnings("unused") int j=0,min=53,value=0,k=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; k=i; } } return k; } }
這一部分要是對學生信息文件的具體處理。
package xinxi; public class Student implements Comparable<Student> { private String name; private String number ; private String sex ; private int age; private String province; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return number; } public void setnumber(String number) { this.number = number; } public String getsex() { return sex ; } public void setsex(String sex ) { this.sex =sex ; } public int getage() { return age; } public void setage(int age) { this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } 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"; } }
3.目前程序設計存在的困難與問題:在文件的讀取方面存在必定的問題,此外數據處理方面的轉換也有相應的問題。
l 實驗九編程練習2總結(從程序整體結構說明、模塊說明,目前程序設計存在的困難與問題三個方面闡述)。
1.程序整體結構說明
2.模塊說明:
這一部分主要完成了隨機生成數和利用switch語句對四則運算的基本操做
package jisuan; import java.util.Scanner; public class Jisuan { public static void main(String[] args) { Scanner in = new Scanner(System.in); int sum = 0; for (int i = 0; i < 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int d = (int) Math.round(Math.random() * 3); switch (d) { case 0: if(b!=0) { System.out.println(a + "/" + b + "="); int c = in.nextInt(); if (c == a / b) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } }else { System.out.println("此表達式錯誤"); } break; case 1: System.out.println(a + "+" + b + "="); int c0 = in.nextInt(); if (c0 == a + b) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 2: System.out.println(a + "-" + b + "="); int c1 = in.nextInt(); if (c1 == a + b) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 3: System.out.println(a + "*" + b + "="); int c2 = in.nextInt(); if (c2 == a + b) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; } } System.out.println("你的得分爲" + sum); } }
shuchu部分主要完成了將程序運算結果以txt文件輸出
package jisuan; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class shuchu { public static void main(String[] args) { Scanner in = new Scanner(System.in); Jisuan counter = new Jisuan(); PrintWriter out = null; try { out = new PrintWriter("shu.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.目前程序設計存在的困難與問題:將程序運算結果以txt文件輸出方面存在問題。
編程練習2:採用泛型程序設計技術改進實驗九編程練習2,使之可處理實數四則運算,其餘要求不變。
代碼以下:
package jisuan; import java.io.*; import java.io.PrintWriter; import java.util.Scanner; public class Jisuan { 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(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( 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( 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( 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(); } }
package jisuan; 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; } }
實驗結果以下圖
實驗總結:理解掌握了泛型類的定義與使用,泛型方法的聲明與使用;泛型接口的定義與實現;此外,對上次實驗的總結反思方面,從中發現了本身的不少不足,尤爲是四則運算的編程,相比上次實驗,從中認識到了不少不足,經過改正,完善了上次沒有將程序運行結果以txt文件輸出的不足。並且經過此次對泛型類的學習,將其與四則運算的編程結合起來,使的四則運算的程序更加完整,能夠實現各類數據類型的運算。有了很大的提高,讓我意識到要不斷對以前學過的內容進行反思總結,不斷完善以前的不足,這樣纔有提高。