第十週Java實驗作業
實驗十 泛型程式設計技術
實驗時間 2018-11-1
1、實驗目的與要求
(1) 理解泛型概念;
泛型:也稱引數化型別,就是在定義類,介面和方法時,通過型別引數只是將要處理的型別物件。(如ArrayList類)
(2) 掌握泛型類的定義與使用;
一個泛型類,就是具有一個或者多個型別變數的類,即建立用型別作為引數的類。一個泛型類定義格式如下:
class Generics(K,V);
其中K和V是類中的可變型別的引數。
(3) 掌握泛型方法的宣告與使用;
泛型方法:除了泛型類之外,還可以只單獨定義一個方法作為泛型方法,用於指定泛型引數或者返回值為泛型型別。,留待方法呼叫時確定。
泛型方法可以宣告在泛型類中,也可以宣告在普通類中。
public class ArrayTool
{
public static <E> void insert (E[] ,int i)
{
......
}
Public static<E> E valueAt(E[] e,int i)
{
...
}
}
(4) 掌握泛型介面的定義與實現;
定義:
public interface IPool<T>
{
T get();
Int add(T t);
}
實現:
public class GenericPool<T> implements IPool<T>
{
...
}
public class GenericPool implements IPool<Account>
{
...
}
(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> //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" };//初始化一個String型別的陣列 Pair<String> mm = ArrayAlg.minmax(words);//通過類名呼叫minmax方法。 //minmax的返回值是Pair<String>型別的 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 //例項化以後的Pair物件(普通方法) { 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:String類陣列a[]的一個屬性 { if (min.compareTo(a[i]) > 0) min = a[i];//compareTo:陣列的遍歷,通過Ascll碼進行比較 if (max.compareTo(a[i]) < 0) max = a[i]; //按照字典排序(比較的是字母的ascll編碼,大寫字母的值比較小 } return new Pair<>(min, max);//返回一個Pair型別的物件。(將這兩個資料打包) } }
執行結果:
測試程式2:
l 編輯、除錯執行教材315頁 PairTest2,結合程式執行結果理解程式;
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[] 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)//泛型方法 //使用extends關鍵字為型別變數設定上界 { 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;//必須設定為null,否則會出現空指標異常 } public Pair(T first, T second)//構造器含引數,first和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) { //建立了manger類物件 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) //Pair<? extends Employee>表示任何泛型Pair型別,它的型別引數是Emplooy的子類。? 萬用字元 { 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 swapHelper萬用字元型別 } // 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); } }
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; } }
執行結果:
實驗2:程式設計練習:
程式設計練習1:實驗九程式設計題總結
l 實驗九程式設計練習1總結(從程式總體結構說明、模組說明,目前程式設計存在的困難與問題三個方面闡述)。
程式結構:
Indentity 和 使用了介面的Student類
package 小陳9; 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 ; } @Override public int compareTo(Student other) { // TODO Auto-generated method stub return this.name.compareTo(other.getName()); }//compareTo方法比較姓名 public String toString() { return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; } }
package 小陳9; 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 Identity{ private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("C:/身份證號.txt"); try { //利用try 。。 catch 語句進行異常處理 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) { 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("0.退出"); int status = scanner.nextInt(); switch (status) { 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 0: status = 0; System.out.println("程式已退出!"); break; default: System.out.println("輸入錯誤"); } } }//選擇具體操作 public static int agenear(int age) { int 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; }//找到年齡最大和最小者 }
程式設計存在的困難與問題:
(1)程式設計能力差,對程式碼的熟悉和了解遠遠不夠,應該多加練習。
(2)看到問題不會分析,不能很快從中提取出主要的變數和要進行的操作
l 實驗九程式設計練習2總結(從程式總體結構說明、模組說明,目前程式設計存在的困難與問題三個方面闡述)。
程式結構:
yunsuan類 和 jieguo類
public class yunsuan { public static void main(String[] args) { Scanner in = new Scanner(System.in); Pair student=new Pair(); PrintWriter out = null; try { out = new PrintWriter("text.txt"); } catch (FileNotFoundException e) { 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 c= (int) Math.round(Math.random() * 3); //生成隨機數 , 用於生成四則運算題目 ,其中c 用於switch語句,生成四則運算的種類
switch(c) { 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 == student.division(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break; case 1: System.out.println(i+": "+a+"*"+b+"="); int D = in.nextInt(); out.println(a+"*"+b+"="+D); if (D == student.multiply(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break; case 2: System.out.println(i+": "+a+"+"+b+"="); int E = in.nextInt(); out.println(a+"+"+b+"="+E); if (E == student.plus(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break ; case 3: System.out.println(i+": "+a+"-"+b+"="); int F = in.nextInt(); out.println(a+"-"+b+"="+F); if (F == student.minus(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break ; } }//生成四則運算題目,並判斷回答是否正確 System.out.println("成績"+sum); out.println("成績:"+sum); out.close();
//輸出結果
} }
*public class jieguo { 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)text檔案的輸出存在問題
(2)介面應用存在問題,對於使用介面設計程式不能熟練掌握。
程式設計練習2:採用泛型程式設計技術改進實驗九程式設計練習2,使之可處理實數四則運算,其他要求不變。
package 小陳1; public class Pair<T> { private T a; private T b; public Pair() { a = null; b = null; } public Pair(T a,T b) { this.a = a; this.b = b; } public T getA() { return a; } public T getB() { return b; } public int plus(int a,int b) { return a+b; } public int minus(int a,int b) { return a-b; } public int multiply(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; } }
package 小陳1; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class yunsuan { public static void main(String[] args) { Scanner in = new Scanner(System.in); Pair student=new Pair(); PrintWriter out = null; try { out = new PrintWriter("text.txt"); } catch (FileNotFoundException e) { 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 c= (int) Math.round(Math.random() * 3); switch(c) { 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 == student.division(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break; case 1: System.out.println(i+": "+a+"*"+b+"="); int D = in.nextInt(); out.println(a+"*"+b+"="+D); if (D == student.multiply(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break; case 2: System.out.println(i+": "+a+"+"+b+"="); int E = in.nextInt(); out.println(a+"+"+b+"="+E); if (E == student.plus(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break ; case 3: System.out.println(i+": "+a+"-"+b+"="); int F = in.nextInt(); out.println(a+"-"+b+"="+F); if (F == student.minus(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break ; } }//生成四則運算題目,並判斷回答是否正確 System.out.println("成績"+sum); out.println("成績:"+sum); out.close(); } }
總結:本週學習了泛型別程式設計,瞭解到泛型的主要目標是實現Java的型別安全。其主要使用在類,介面,方法中。提高了程式碼的重用性。存在的問題在於對泛型程式設計的使用不太熟練,還需要繼續進行學習。