第十周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的类型安全。其主要使用在类,接口,方法中。提高了代码的重用性。存在的问题在于对泛型程序设计的使用不太熟练,还需要继续进行学习。
第十周Java实验作业的更多相关文章
- 第十八周java实验作业
实验十八 总复习 实验时间 2018-12-30 1.实验目的与要求 (1) 综合掌握java基本程序结构: (2) 综合掌握java面向对象程序设计特点: (3) 综合掌握java GUI 程序设 ...
- 第十五周java实验作业
实验十五 GUI编程练习与应用程序部署 实验时间 2018-12-6 1.实验目的与要求 (1) 掌握Java应用程序的打包操作: Java程序的打包,程序编译完成后,程序员将.class文件压缩打 ...
- 第十六周Java实验作业
实验十六 线程技术 实验时间 2017-12-8 1.实验目的与要求 (1) 掌握线程概念: 多线程是进程执行过程中产生的多条执行线索,线程是比进程执行更小的单位. 线程不能独立存在,必须存在于进程 ...
- 第十二周java实验作业
实验十二 图形程序设计 实验时间 2018-11-14 1.实验目的与要求 (1) 掌握Java GUI中框架创建及属性设置中常用类的API: Java的集合框架实现了对各种数据结构的封装. jav ...
- 第十四周java实验作业
实验十四 Swing图形界面组件 实验时间 20178-11-29 1.实验目的与要求 (1) 掌握GUI布局管理器用法: 在java中的GUI应用 程序界面设计中,布局控制通过为容器设置布局管理器 ...
- 第十一周Java实验作业
实验十一 集合 实验时间 2018-11-8 1.实验目的与要求 (1) 掌握Vetor.Stack.Hashtable三个类的用途及常用API: Vector类类似长度可变的数组,其中只能存放对 ...
- 第十七周Java实验作业
实验十七 线程同步控制 实验时间 2018-12-10 1.实验目的与要求 (1) 掌握线程同步的概念及实现技术: 多线程并发运行不确定性问题解决方案:引入线程同步机制,使得另一线程使用该方法,就只 ...
- 第九周Java实验作业
实验九 异常.断言与日志 实验时间 2018-10-25 1.实验目的与要求 (1) 掌握java异常处理技术: Java的异常处理机制可以控制程序从错误产生的位置转移到能够进行错误处理的位置. Ja ...
- 第八周Java实验作业
实验六 接口的定义与使用 实验时间 2018-10-18 1.实验目的与要求 (1) 掌握接口定义方法: 声明: public interface 接口名 {...} 接口体中包含常量定义和方法定义 ...
随机推荐
- 复合文字(Compound Literals)
复合文字(Compound Literals) 阅读代码时发现了这行 1 setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&(int){1},sizeof(in ...
- Redis-输入输出缓冲区
一.client list id:客户端连接的唯一标识,这个id是随着Redis的连接自增的,重启Redis后会重置为0addr:客户端连接的ip和端口fd:socket的文件描述符,与lsof命令结 ...
- Java-Springboot-集成spring-security简单示例(Version-springboot-2-1-3-RELEASE
使用Idea的Spring Initializr或者SpringBoot官网下载quickstart 添加依赖 1234 <dependency><groupId>org.sp ...
- VSCode通过git上传代码
最近也是在不断学习中,接触VSCode时间不长,很多东西也是在学习,所以这里记录下VSCode通过git上传代码,以防之后忘记. 我用的的VSCode版本 起初建立仓库的时候通过命令:(这个是我网上搜 ...
- java反序列化-ysoserial-调试分析总结篇(3)
前言: 这篇文章主要分析commoncollections3,这条利用链如yso描述,这个与cc1类似,只是反射调用方法是用的不是invokeTransformer而用的是InstantiateTra ...
- 名企6年Java程序员的工作感悟,送给迷茫的你
程序员从开始选择到坚持下去,工作了六年对一个程序员意味什么?在职位上:高级开发工程师?架构师?技术经理?or ... ?在能力上:各种编码无压力?核心代码无压力?平台架构无压力? or ... fuc ...
- 奉上简单的.Net后端开发模板
假定一个场景,开始做开发的你,领导走到你的面前说道:"小伙子,看了简历和最近的工作表现,很不错,现在交给一个任务,开发一个简单的CMS后端接口吧,前端有人配合你",当时你内心读白: ...
- 一文了解各大图数据库查询语言(Gremlin vs Cypher vs nGQL)| 操作入门篇
文章的开头我们先来看下什么是图数据库,根据维基百科的定义:图数据库是使用图结构进行语义查询的数据库,它使用节点.边和属性来表示和存储数据. 虽然和关系型数据库存储的结构不同(关系型数据库为表结构,图数 ...
- safari坑之 回弹
博客地址: https://www.seyana.life/post/20 今天在使用safari浏览博客的时候, 发现在拉至顶部并产生回弹之后,头部导航隐藏了, 除非在上拉的时候,刚好达到顶部而不超 ...
- Nacos 数据持久化 mysql8.0
一.问题描述 直接下载的稳定版本nacos编译后的文件,不支持mysql8及其以上版本,按照官网文档:https://nacos.io/zh-cn/docs/deployment.html 执行完成之 ...