第8章泛型程式設計學習總結
第一部分:理論知識
主要內容: 什麼是泛型程式設計
泛型類的宣告及例項化的方法
泛型方法的定義
泛型介面的定義
泛型型別的繼承規則
萬用字元型別及使用方法
1:泛型類的定義
(1) 一個泛型類(generic class)就是具有一個或多個型別變數的類,即建立用型別作為引數的類。如一個泛型類定義格式如下:class Generics<K,V>其中的K和V是類中的可變型別引數。如:
public class Pair{
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)Pair類引入了一個型別變數T,用尖括號(<>)括起來,並放在類名的後面。泛型類可以有多個型別變數。例如:public class Pair<t, u=""> { … }
(3) 類定義中的型別變數用於指定方法的返回型別以及域、區域性變數的型別。
2.泛型方法的宣告
(1)泛型方法
– 除了泛型類外,還可以只單獨定義一個方法作為泛型方法,用於指定方法引數或者返回值為泛型型別,留待方法呼叫時確定。
– 泛型方法可以宣告在泛型類中,也可以宣告在普通類中。
public class ArrayTool
{
public static void insert(
E[] e, int i)
{
//請自己新增程式碼
}
public static E valueAt(
E[] e , int i)
{
//請自己新增程式碼
}
}
3.泛型介面的定義
(1)定義
public interface IPool
{
T get();
int add(T t);
}
(2)實現
public class GenericPool implements IPool
{
…
}
public class GenericPool implements IPool
{
…
}
4.泛型變數的限定
(1) 定義泛型變數的上界
public class NumberGeneric< T extends Number>
(2) 泛型變數上界的說明
上述宣告規定了NumberGeneric類所能處理的泛型變數型別需和Number有繼承關係;
extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面;
(3)< T extends BoundingType> 表示T應該是繫結型別的子型別。 一個型別變數或萬用字元可以有多個限定,限定型別用“&”分割。例如:< T extends Comparable & Serializable >
(4) 定義泛型變數的下界
List cards = new ArrayList();
(5) 泛型變數下界的說明
– 通過使用super關鍵字可以固定泛型引數的型別為某種型別或者其超類
– 當程式希望為一個方法的引數限定型別時,通常可以使用下限萬用字元
public static void sort(T[] a,Comparator c)
{ …
}
5.萬用字元型別
萬用字元
– “?”符號表明引數的型別可以是任何一種型別,它和引數T的含義是有區別的。T表示一種未知型別,而“?”表示任何一種型別。這種萬用字元一般有以下三種用法:
– 單獨的?,用於表示任何型別。
– ? extends type,表示帶有上界。
– ? super type,表示帶有下界。
第二部分:實驗部分
實驗十 泛型程式設計技術
實驗時間 2018-11-1
1、實驗目的與要求
(1) 理解泛型概念;
(2) 掌握泛型類的定義與使用;
(3) 掌握泛型方法的宣告與使用;
(4) 掌握泛型介面的定義與實現;
(5)瞭解泛型程式設計,理解其用途。
2、實驗內容和步驟
實驗1: 匯入第8章示例程式,測試程式並進行程式碼註釋。
測試程式1:
l 編輯、除錯、執行教材311、312頁 程式碼,結合程式執行結果理解程式;
l 在泛型類定義及使用程式碼處添加註釋;
l 掌握泛型類的定義及使用。
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" };
//ArrayAlg呼叫靜態方法minmax;
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)//定義靜態泛型方法,將型別變數例項化為String;
{
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);//返回一個例項化後的類物件;
}
}
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; }
// 構造泛型方法,構造方法的入口引數(first, second)型別為泛型T;
public Pair(T first, T second) { this.first = first; this.second = second; }
//定義泛型方法,型別變數T指定了訪問方法的返回值和入口引數的型別;
public T getFirst() { return first; }
public T getSecond() { return second; }
//泛型方法,構造方法的入口引數型別為泛型T;
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
測試程式2:
l 編輯、除錯執行教材315頁 PairTest2,結合程式執行結果理解程式;
l 在泛型程式設計程式碼處新增相關注釋;
l 掌握泛型方法、泛型變數限定的定義及用途。
package pair2; /**
* @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; }
// 構造泛型方法,構造方法的入口引數(first, second)型別為泛型T;
public Pair(T first, T second) { this.first = first; this.second = second; }
//定義泛型方法,型別變數T指定了訪問方法的返回值和入口引數的型別;
public T getFirst() { return first; }
public T getSecond() { return second; }
//泛型方法,構造方法的入口引數型別為泛型T;
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
package pair2;
//import PairTest1.Pair;
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
};
//ArrayAlg呼叫靜態方法minmax,
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
*/
//構造泛型方法;限定型別變數,型別變數T是Comparable類的子類,
public static <T extends Comparable> Pair<T> minmax(T[] a)
{
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);//返回一個例項化泛型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繼承父類 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.00 2004-05-10
* @author Cay Horstmann
*/
public class Pair<T> //定義泛型類,型別變數為T;
{
private T first;
private T second; public Pair() { first = null; second = null; }
// 構造泛型方法,構造方法的入口引數(first, second)型別為泛型T;
public Pair(T first, T second) { this.first = first; this.second = second; }
//定義泛型方法,型別變數T指定了訪問方法的返回值和入口引數的型別;
public T getFirst() { return first; }
public T getSecond() { return second; }
//泛型方法,構造方法的入口引數型別為泛型T;
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泛型類物件(泛型變數T預設為int型,並將其傳遞給型別變數T為Manager的類變數buddies;
Pair<Manager> buddies = new Pair<>(ceo, cfo);
printBuddies(buddies); ceo.setBonus(1000000);
cfo.setBonus(500000);
Manager[] managers = { ceo, cfo }; Pair<Employee> result = new Pair<>();//建立一個Pair類物件,並將其傳遞給型別變數T為Employee的類變數 result;
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());
} //?:下限萬用字元;限定型別變數的下界為Employee類;
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.");
}
//?:下限萬用字元;限定型別變數的下界為Manager類;
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);
}
//?:下限萬用字元;限定泛型類Pair型別變數的下界為Manager類;
public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
{
minmaxBonus(a, result);
PairAlg.swapHelper(result); //swapHelper捕獲萬用字元型別 ;
}
// 不能寫: public static <T super manager> ...
} class PairAlg
{
public static boolean hasNulls(Pair<?> p)//限定泛型類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總結(從程式總體結構說明、模組說明,目前程式設計存在的困難與問題三個方面闡述)。
package shiyan9;
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 Search{ private static ArrayList<Person> Personlist1;
public static void main(String[] args) { Personlist1 = new ArrayList<>(); Scanner scanner = new Scanner(System.in);
File file = new File("E:\\面向物件程式設計Java\\實驗\\實驗六\\身份證號.txt"); 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("******************************************");
System.out.println("1:按姓名字典順序輸出資訊;");
System.out.println("2:查詢最大年齡與最小年齡人員資訊;");
System.out.println("3:按省份找你的同鄉;");
System.out.println("4:輸入你的年齡,查詢年齡與你最近人的資訊;");
System.out.println("5:退出");
System.out.println("******************************************");
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; } }
Search
package shiyan9; 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"; } }
Person
(1)程式設計練習1總結:
程式總體結構:主類(Search)和介面(Person);
模組說明:(1)主類Search:讀取檔案模組;
Try/catch模組:監視可能出現的異常;捕捉處理異常;
Switch/case模組匹配選擇5種具體操作;
(2)介面(Person):
屬性宣告模組;
構造方法模組:getname,setname, getid,setid,getage,setage,getsex,setsex,getbirthplace,setbirthplace,compareTo等;
目前存在的困難與問題: 檔案讀取路徑的設定影響到能否找到檔案;
不論是語法,還是主要的技術(如介面)方面不是嫻熟,有些顯而易見的東西不能立馬想到;
構想正確的設計思路;
l 實驗九程式設計練習2總結(從程式總體結構說明、模組說明,目前程式設計存在的困難與問題三個方面闡述)。
package a; import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner; import org.w3c.dom.css.Counter; public class Main{
public static void main(String[] args) { Scanner in = new Scanner(System.in);
counter counter=new counter();
PrintWriter output = null;
try {
output = new PrintWriter("result.txt");
} catch (Exception e) {
//e.printStackTrace();
}
int sum = 0; for (int i = 1; i < 11; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int type = (int) Math.round(Math.random() * 4); switch(type)
{
case 1:
System.out.println(i+": "+a+"/"+b+"=");
while(b==0){
b = (int) Math.round(Math.random() * 100);
}
double c = in.nextDouble();
output.println(a+"/"+b+"="+c);
if (c == counter.Chu(a, b))
{
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
} break; case 2:
System.out.println(i+": "+a+"*"+b+"=");
int c1 = in.nextInt();
output.println(a+"*"+b+"="+c1);
if (c1 == counter.Cheng(a, b)) {
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}break;
case 3:
System.out.println(i+": "+a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2);
if (c2 == counter.Jia(a, b)) {
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}break ;
case 4:
System.out.println(i+": "+a+"-"+b+"=");
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == counter.Jian(a, b)) {
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}break ; } }
System.out.println("成績"+sum);
output.println("成績:"+sum);
output.close(); }
}
Main
package a; public class counter {
private int a;
private int b; public int Jia(int a,int b)
{
return a+b;
}
public int Jian(int a,int b)
{
if((a-b)<0)
return 0;
else
return a-b;
}
public int Cheng(int a,int b)
{
return a*b;
}
public int Chu(int a,int b)
{
if(b!=0)
return a/b;
else
return 0;
} }
counter
程式設計練習2總結:
程式結構:主類Main和子類counter兩大部分;
模組說明:Main類:
(1) 建檔案字元流,檔案輸出模組,將out結果輸出到result.txt中;
(2) try/catch模組捕獲處理異常;
(3) Switch//case模組:隨機生成a,b兩個運算元,匹配選擇加減乘除四種具體操作;
(4) 輸出總成績;
子類counter類:
(1) 屬性宣告;
(2) 構造方法;
程式設計存在的困難與問題:
1.沒有全面考慮小學生的實際狀況:減法演算法結果可能出現負數的情況,以及除法的運算結果直接取整輸出,都不符合小學生的學習範圍;
2.程式設計過程中,我在變數的 使用範圍中出現了問題;
3.結果輸出到檔案中;
4.設計思路比較難;
程式設計練習2:採用泛型程式設計技術改進實驗九程式設計練習2,使之可處理實數四則運算,其他要求不變。
package a; import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner; //import org.w3c.dom.css.Counter; public class Main{
public static void main(String[] args) { Scanner in = new Scanner(System.in);
counter Counter=new counter();
PrintWriter output = null;
try {
output = new PrintWriter("result.txt");
} catch (Exception 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 type = (int) Math.round(Math.random() * 4); switch(type)
{
case 1: System.out.println(i+": "+a+"/"+b+"=");
while(b== 0&& a%b!=0)
{
b = (int) Math.round(Math.random() * 100);
a = (int) Math.round(Math.random() * 100);
} int c = in.nextInt();
output.println(a+"/"+b+"="+c);
if (c == Counter.Chu(a, b))
{
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}
break; case 2:
System.out.println(i+": "+a+"*"+b+"=");
int c1 = in.nextInt();
output.println(a+"*"+b+"="+c1);
if (c1 == Counter.Cheng(a, b)) {
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}
break;
case 3:
System.out.println(i+": "+a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2); if (c2 == Counter.Jia(a, b)) {
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}
break ; case 4: while (a < b) {
int x=0;
x=b;
b=a;
a=x;
}
System.out.println(i+": "+a+"-"+b+"=");
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == Counter.Jian(a, b))
{
sum += 10;
System.out.println("恭喜答案正確!");
}
else {
System.out.println("答案錯誤!");
}
break ; } }
System.out.println("成績"+sum);
output.println("成績:"+sum);
output.close(); }
}
package a; public class counter<T>{
private T a;
private T b; public counter(T a, T b) {
this.a = a;
this.b = b;
} public counter() {
// TODO Auto-generated constructor stub
} public int Jia(int a,int b)
{
return a+b;
}
public int Jian(int a,int b)
{
return a-b; }
public int Cheng(int a,int b)
{
return a*b;
}
public int Chu(int a,int b)
{
if (b!= 0 && a%b==0)
return a / b;
else
return 0; } }
主要是對於除法和減法的修改,過濾掉一些不合適的資料;
第三部分:總結
1.上泛型理論課的時候,我以為我掌握的差不多了,用的時候還是多多少少有這樣那樣的問題,可能有些操作我沒練習過也就沒發現一些隱藏的問題和疑惑。
2.之前讀程式碼,敲程式碼的時候雖然會總結,但一直不怎麼重視反思總結,但這次這麼仔細的,以老師給的這種步驟去重新審視總結,感覺很不錯,也積累了一種學習方法;
3.拿到一個問題後的解決思路是非常重要的!!!