理论知识:
1.泛型类的定义,一个泛型类就是具有一个或多 个类型变量的类,即创建用类型作为参数的类。 如: class Generics<K,V>;
2.泛型方法,除了泛型类外,还可以只单独定义一个方法作为泛型方法,用于指定方法参数或者返回值为 泛型类型,留待方法调用时确定。泛型方法可以声明在泛型类中,也可以声明在普通类中。
3.泛型接口的定义,public interface IPool <T> { T get(); int add(T t); }
4.泛型变量的限定,上界:public class NumberGeneric< T extends Number>
下界:List<? superCashCard> cards = new ArrayList<T>();
5.通配符的类型限定,Pair<? extends Employee>
1、实验目的与要求
(1) 理解泛型概念;
(2) 掌握泛型类的定义与使用;
(3) 掌握泛型方法的声明与使用;
(4) 掌握泛型接口的定义与实现;
(5)了解泛型程序设计,理解其用途。
2、实验内容和步骤
实验1:
测试程序1:
Pair.java
package pair1; /** * @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; } }
PairTest.java
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方法 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];//字符串对象比较,ASCII码比较 if (max.compareTo(a[i]) < 0) max = a[i]; } return new Pair<>(min, max);//泛型类作为返回值 } }
输出结果:
测试程序2:
PairTest2.java
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 };//初始化LocalDate对象数组 Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);//通过类名调用minmax方法 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接口的类,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:
Employee.java
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);//buddies里Manager对象 printBuddies(buddies); ceo.setBonus(1000000); cfo.setBonus(500000); Manager[] managers = { ceo, cfo }; Pair<Employee> result = new Pair<>();//result里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 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)//该方法的参数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) //参数p任意一种类型的对象 { swapHelper(p); } public static <T> void swapHelper(Pair<T> p)//p调用方法时指定的一种类型T的对象 { T t = p.getFirst(); p.setFirst(p.getSecond()); p.setSecond(t); } }
Employee.java
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; } }
Manager.java
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:实验九编程题总结
总结1:
程序总体结构说明:Identify类和Person类
模块说明:Identify类和Person类
Identify.java
package 第八周实验; 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 Identify { private static ArrayList<Person> personlist; public static void main(String[] args) { personlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("E:\身份证号.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 hometown = linescanner.nextLine(); Person person = new Person(); person.setName(name); person.setnumber(number); person.setsex(sex); int A = Integer.parseInt(age); person.setage(A); person.sethometown(hometown); 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("0.按姓名字典序输出人员信息;"); System.out.println("1.查询最大年龄人员信息;;"); System.out.println("2.查询最小年龄人员信息;"); System.out.println("3.寻找同乡;"); System.out.println("4.寻找年龄相近的人;"); System.out.println("5.退出。"); String W = scanner.next(); switch(W) { case "0": Collections.sort(personlist); System.out.println(personlist.toString()); break; case "1": int a = 0; int j, c1 = 0, d1 = 0; for (int i = 1; i < personlist.size(); i++) { j = personlist.get(i).getage(); if (j > a) { a = j; c1 = i; } } System.out.println("年龄最大:" + personlist.get(c1)); break; case "2": int b = 100; int j1,c2 = 0,d2 = 0; for (int i = 1; i < personlist.size(); i++) { j1 = personlist.get(i).getage(); if (j1 < b) { b = j1; d2 = i; } } System.out.println("年龄最小:" + personlist.get(d2)); break; case "3": System.out.println("籍贯:"); String search = scanner.next(); String place = search.substring(0, 3); int i = 0; for (; i < personlist.size(); i++) { if (personlist.get(i).gethometown().substring(1, 4).equals(place)) System.out.println("你的同乡是:" + personlist.get(i)); } break; case "4": System.out.println("年龄:"); int yourage = scanner.nextInt(); int nearaga = agenear(yourage); int value = yourage - personlist.get(nearaga).getage(); System.out.println("" + personlist.get(nearaga)); break; case "5": isTrue = false; System.out.println("退出程序!"); break; default: System.out.println("检查输入!"); } } } public static int agenear(int age) { int j = 0, b = 53, value = 0, c = 0; for (int i = 0; i < personlist.size(); i++) { value = personlist.get(i).getage() - age; if (value < 0) value = -value; if (value < b) { b = value; c = i; } } return c; } }
Person.java
public class Person implements Comparable<Person> { private String name; private String number; private String sex; private int age; private String hometown; 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 gethometown() { return hometown; } public void sethometown(String hometown) { this.hometown = hometown; } public int compareTo(Person o) { return this.name.compareTo(o.getName()); } public String toString() { return name + " " + sex + " " + age + " " + number + " " + hometown + " "; } }
目前程序设计存在的困难与问题:
1.对于代码功能的使用不熟练;
2.对于编写代码时,关于代码整体构造没有一个清晰的想法;
3.总是无法写出完全符合题目要求的代码,总出现报错;
总结2:
程序总体结构说明 : Exam类 main函数
模块说明:Exam类
Exam.java
package 计算器; import java.util.Scanner; import java.util.Random; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Exam{ int sum; public static void main(String[] args) { Exam exam = new Exam(); exam.sum = 0; Random r = new Random (); PrintWriter output = null; try { output = new PrintWriter("E://text.txt"); } catch (Exception e) { e.printStackTrace(); } for(int i = 0;i<10;i++) { exam.score(); } System.out.println("你的总分为:"+exam.sum); output.println("你的总分为:"+exam.sum); output.close(); } private void score() { Random r = new Random (); int m; m = (int) Math.round(Math.random() * 4); switch(m) { case 0: int a,b,c; a = r.nextInt() % 100; b = r.nextInt() % 100; System.out.println(a + "+" + "(" + b + ")="); Scanner x = new Scanner(System.in); c = x.nextInt(); if(c != a+b) System.out.println("答案错误!"); else { System.out.println("答案正确!"); sum += 10; } break; case 1: int o,p,q; o = r.nextInt() % 100; p = r.nextInt() % 100; System.out.println(o + "-" + "(" + p + ")="); Scanner y = new Scanner(System.in); q = y.nextInt(); if(q != o-p) System.out.println("答案错误!"); else { System.out.println("答案正确!"); sum += 10; } break; case 2: int d,e,f; d = r.nextInt() % 100; e = r.nextInt() % 100; System.out.println(d + "*" +"("+ e + ")" + "="); Scanner z = new Scanner(System.in); f = z.nextInt(); if(f != d * e) System.out.println("答案错误!"); else { System.out.println("答案正确!"); sum += 10; } break; case 3: int h,i,j; h = r.nextInt() % 100; i = r.nextInt() % 100; if(i == 0) i++; System.out.println(h + "/" +"("+ i + ")" + "="); Scanner u = new Scanner(System.in); j = u.nextInt(); if(j != h/i) System.out.println("答案错误!"); else { System.out.println("答案正确!"); sum += 10; } break; } } }
目前程序设计存在的困难与问题:
1.代码不完美,并不完全符合题目要求;
2.计算题的除法运算存在问题,在上面的代码中,如果除数 i 为0,则 i 累加1,而不是随机在给出一个不为0的数。
3.运行多次,会出现只给出8道题或9道题的情况。
编程练习2:
Student.java
package 计算器; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Studentexam { public static void main(String[] args) { Scanner in = new Scanner(System.in); Studentexam s = new Studentexam(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); } catch (FileNotFoundException e) { System.out.println("文件输出失败"); 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; Random rand = new Random(); m = (int) rand.nextInt(4) + 1; switch (m) { case 1: 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 c0 = in.nextInt(); out.println(a + "/" + b + "=" + c0); if (c0 == s.chufa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; case 2: System.out.println(a + "*" + b + "="); int c = in.nextInt(); System.out.println(a + "*" + b + "=" + c); if (c == s.chengfa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; case 3: System.out.println(a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == s.jiafa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; case 4: while (a < b) { b = (int) Math.round(Math.random() * 100); } System.out.println(a + "-" + b + "="); int c2 = in.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == s.jianfa(a, b)) { sum += 10; System.out.println("回答正确!"); } else { System.out.println("回答错误!"); } break; } } System.out.println("你的总成绩为" + sum); out.println("你的总成绩为" + sum); out.close(); } public int jiafa(int a,int b) { return a + b; } public int jianfa(int a, int b) { return a - b; } public int chengfa(int a, int b) { return a * b; } public int chufa(int a, int b) { if (b != 0 && a%b==0) return a / b; else return 0; } }
Student.java
package 计算器; public class Student<T> { private T a; private T b; public Student() { a = null; b = null; } public Student(T a, T b) { this.a = a; this.b = b; } }
输出结果:
总结:
本周,我们学习了泛型程序设计,虽然对于泛型的定义不难理解但是我觉得自己的编程能力要比读代码的能力弱,在写程序时脑子对于程序构造里没有一个清晰完整的结构,总是想一点写一点,平时对于Java的训练太少,做PTA中的编程题时总是习惯用C语言去解决,如果想要更加熟练地运用Java,我还需要更加努力的学习。