201871010101-陈来弟《面向对象程序设计(Java)》第十一周学习总结

实验九  泛型程序设计技术

实验时间 2019-11-8

第一部分:理论基础知识

1.什么是泛型类

泛型是具有占位符(类型参数)的类、结构、接口和方法,这些占位符是类、结构、接口和方法所存储或使用的一个或多个类型的占位符。泛型集合类可以将类型参数用作它所存储的对象的类型的占位符;类型参数作为其字段的类型和其方法的参数类型出现。泛型方法可以将其类型参数用作其返回值的类型或者其形参的类型之一。下面的代码阐释一个简单的泛型类定义。在创建泛型类的实例时,会指定实际类型来替换类型参数。这会建立一个新的泛型类,称为构造泛型类,选定的类型将替换所有出现的类型参数。最后得到按照您选择的类型定制的类型安全的类。     

“泛型类型定义”是用作模板的类、结构或接口声明,其中具有该类、结构或接口声明可以包含或使用的类型的占位符。例如,Dictionary 类可以包含两种类型:键和值。因为它只是一个模板,您不能创建作为泛型类型定义的类、结构或接口的实例。

“泛型类型参数”或称“类型参数”是泛型类型或方法定义中的占位符。Dictionary 泛型类型具有两个类型参数:TKey 和 TValue,分别表示其键和值的类型。

“构造泛型类型”或称“构造类型”是为泛型类型定义的泛型类型参数指定类型得到的结果。

“泛型类型参数”是替换泛型类型参数的任何类型。

一般术语“泛型类型”包括构造类型和泛型类型定义。

“约束”是加在泛型类型参数上的限制。例如,可以将类型参数限制为实现 IComparer 泛型接口的类型以确保可以对该类型的实例进行排序。还可以将类型参数限制为具有特定基类的类型、具有默认构造函数的类型或是引用类型或值类型。泛型类型的用户不能替换不满足这些约束的类型参数。

2.“泛型方法定义”是具有两个参数列表的方法:一个泛型类型参数列表和一个形参列表。类型参数可以作为返回类型或形参的类型出现。泛型方法可以出现在泛型或非泛型类型上。需要注意的是,并不是只要方法属于泛型类型,或者甚至是方法的形参的类型是封闭类型的泛型参数,就可以说方法是泛型方法。只有当方法具有它自己的类型参数列表时,才能称其为泛型方法。

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,表示带有下界。

第二部分:实验部分

1、实验目的与要求

(1) 理解泛型概念;

(2) 掌握泛型类的定义与使用;

(3) 了解泛型方法的声明与使用;

(4) 掌握泛型接口的定义与实现;

(5) 理解泛型程序设计,理解其用途。

2、实验内容和步骤

实验1 导入第8章示例程序,测试程序并进行代码注释。

测试程序1:

编辑、调试、运行教材311312页代码,结合程序运行结果理解程序;

在泛型类定义及使用代码处添加注释;

掌握泛型类的定义及使用。

插入代码如下:

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" };
Pair<String> mm = ArrayAlg.minmax(words);//泛型类对象String Pair类,静态方法用类名调用方法,泛型字符串类型,按字典序排序
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 values, or null if a is null or empty
*/
public static Pair<String> minmax(String[] a)//普通方法,返回值是一个实例化的Pair类对象
{
if (a == null || a.length == ) return null;//length是数组的属性值
String min = a[];
String max = a[];
for (int i = ; i < a.length; i++)
{
if (min.compareTo(a[i]) > ) min = a[i];
if (max.compareTo(a[i]) < ) max = a[i];
}
return new Pair<>(min, max);//用泛型类来返回两个值
}
}

运行结果如下:

测试程序2:

编辑、调试运行教材315 PairTest2,结合程序运行结果理解程序;

在泛型程序设计代码处添加相关注释;

了解泛型方法、泛型变量限定的定义及用途。

代码如下:

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.of(, , ), // G. Hopper
LocalDate.of(, , ), // A. Lovelace
LocalDate.of(, , ), // J. von Neumann
LocalDate.of(, , ), // 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 values, or null if a is null or empty
*/
public static <T extends Comparable> Pair<T> minmax(T[] a) //泛型方法,有上界约束
{
if (a == null || a.length == ) return null;
T min = a[];
T max = a[];
for (int i = ; i < a.length; i++)
{
if (min.compareTo(a[i]) > ) min = a[i];
if (max.compareTo(a[i]) < ) max = a[i];
}
return new Pair<>(min, max);
}
}

运行结果如下:

测试程序3:

用调试运行教材335 PairTest3,结合程序运行结果理解程序;

了解通配符类型的定义及用途。

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 / ;
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 = ;
} public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
} public void setBonus(double b)
{
bonus = b;
} public double getBonus()
{
return bonus;
}
}
Pair.java 

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; }
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; }
}
PairTest3.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", , , , );
Manager cfo = new Manager("Sid Sneaky", , , , );
Pair<Manager> buddies = new Pair<Manager>(ceo, cfo); //类型变量
printBuddies(buddies); ceo.setBonus();
cfo.setBonus();
Manager[] managers = { ceo, cfo }; Pair<Employee> result = new Pair<Employee>();//也可以用Manager
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 == ) return;
Manager min = a[];
Manager max = a[];
for (int i = ; 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
}
// can't write public static <T super manager> . . .
} class PairAlg
{
public static boolean hasNulls(Pair<?> p)//?类型变量的通配符,单独的?表示任何一种类型,T表示一种未知类型
//将hasNulls转换成泛型方法
//测试一个pair是否包含一个null引用
{
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结对编程练习,将程序提交到PTA(2019面向对象程序设计基础知识测试题(2)

1 编写一个泛型接口GeneralStack,要求类方法对任何引用类型数据都适用。GeneralStack接口中方法如下:

push(item);            //如item为null,则不入栈直接返回null。

pop();                 //出栈,如为栈为空,则返回null。

peek();                //获得栈顶元素,如为空,则返回null.

public boolean empty();//如为空返回true

public int size();     //返回栈中元素数量

2定义GeneralStack的类ArrayListGeneralStack要求:

ü 类内使用ArrayList对象存储堆栈数据,名为list;

ü 方法: public String toString()//代码为return list.toString();

ü 代码中不要出现类型不安全的强制转换。

3定义Car类,类的属性有:

private int id;

private String name;

方法:Eclipse自动生成setter/getter,toString方法。

4main方法要求

ü 输入选项,有quit, Integer, Double, Car 4个选项。如果输入quit,程序直接退出。否则,输入整数m与n。m代表入栈个数,n代表出栈个数。然后声明栈变量stack。

ü 输入Integer,打印Integer Test。建立可以存放Integer类型的ArrayListGeneralStack。入栈m次,出栈n次。打印栈的toString方法。最后将栈中剩余元素出栈并累加输出。

ü 输入Double ,打印Double Test。剩下的与输入Integer一样。

ü 输入Car,打印Car Test。其他操作与Integer、Double基本一样。只不过最后将栈中元素出栈,并将其name依次输出。

特别注意:如果栈为空,继续出栈,返回null

输入样例

Integer

5

2

1 2 3 4 5

Double

5

3

1.1 2.0 4.9 5.7 7.2

Car

3

2

1 Ford

2 Cherry

3 BYD

quit

输出样例

Integer Test

push:1

push:2

push:3

push:4

push:5

pop:5

pop:4

[1, 2, 3]

sum=6

interface GeneralStack

Double Test

push:1.1

push:2.0

push:4.9

push:5.7

push:7.2

pop:7.2

pop:5.7

pop:4.9

[1.1, 2.0]

sum=3.1

interface GeneralStack

Car Test

push:Car [id=1, name=Ford]

push:Car [id=2, name=Cherry]

push:Car [id=3, name=BYD]

pop:Car [id=3, name=BYD]

pop:Car [id=2, name=Cherry]

[Car [id=1, name=Ford]]

Ford

interface GeneralStack

代码如下:


import java.util.ArrayList;
import java.util.Scanner;

interface GeneralStack<T>{
public T push(T item); //如item为null,则不入栈直接返回null。
public T pop(); //出栈,如为栈为空,则返回null。
public T peek(); //获得栈顶元素,如为空,则返回null.
public boolean empty();//如为空返回true
public int size(); //返回栈中元素数量
}
//定义GeneralStack的子类ArrayListGeneralStack
class ArrayListGeneralStack implements GeneralStack{
ArrayList list=new ArrayList();
@Override
public String toString() {
return list.toString();
}

@Override
public Object pop() {
if (list.size()==0){
return null;
}
return list.remove(list.size()-1);
}
@Override
public Object push(Object item) {
if (list.add(item)){
return item;
}else {
return false;
}
}
@Override
public Object peek() {
return list.get(list.size()-1);
}

@Override
public boolean empty() {
if (list.size()==0){
return true;
}else {
return false;
}
}

@Override
public int size() {
return list.size();
}
}
//定义Car类
class Car{
private int id;
private String name;

@Override
public String toString() {
return "Car [" +
"id=" + id +
", name=" + name +
']';
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Car(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (true){
String s=sc.nextLine();
if (s.equals("Double")){
System.out.println("Double Test");
int count=sc.nextInt();
int pop_time=sc.nextInt();
ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//建立可以存放Double类型的ArrayListGeneralStack
for (int i=0;i<count;i++){
System.out.println("push:"+arrayListGeneralStack.push(sc.nextDouble()));
}
for (int i=0;i<pop_time;i++){
System.out.println("pop:"+arrayListGeneralStack.pop());
}
System.out.println(arrayListGeneralStack.toString());
double sum=0;
int size=arrayListGeneralStack.size();
for (int i=0;i<size;i++){
sum+=(double)arrayListGeneralStack.pop();
}
System.out.println("sum="+sum);
System.out.println("interface GeneralStack");
}
else if (s.equals("Integer")){
System.out.println("Integer Test");
int count=sc.nextInt();
int pop_time=sc.nextInt();
ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//建立可以存放Integer类型的ArrayListGeneralStack
for (int i=0;i<count;i++){
System.out.println("push:"+arrayListGeneralStack.push(sc.nextInt()));
}
for (int i=0;i<pop_time;i++){
System.out.println("pop:"+arrayListGeneralStack.pop());
}
System.out.println(arrayListGeneralStack.toString());
int sum=0;
int size=arrayListGeneralStack.size();
for (int i=0;i<size;i++){
sum+=(int)arrayListGeneralStack.pop();
}
System.out.println("sum="+sum);
System.out.println("interface GeneralStack");
}
else if (s.equals("Car")){
System.out.println("Car Test");
int count=sc.nextInt();
int pop_time=sc.nextInt();
ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//创建可以存放Car类型的ArrayListGeneralStack
for (int i=0;i<count;i++){
int id=sc.nextInt();
String name=sc.next();
Car car = new Car(id,name);
System.out.println("push:"+arrayListGeneralStack.push(car));
}
for (int i=0;i<pop_time;i++){
System.out.println("pop:"+arrayListGeneralStack.pop());
}
System.out.println(arrayListGeneralStack.toString());
if (arrayListGeneralStack.size()>0){
int size=arrayListGeneralStack.size();
for (int i=0;i<size;i++){
Car car=(Car) arrayListGeneralStack.pop();
System.out.println(car.getName());
}
}
System.out.println("interface GeneralStack");
}
else if (s.equals("quit")){
break;
}
}

}
}

 

运行结果如下:

第三部分:实验总结

通过这周的学习,我了解了泛型设计技术的概念,泛型程序设计意味着编写代码可以被很多不同类型的对象所重用,以及它的好处和限制,基本上会运用泛型技术设计程序,但是在很多知识的运用方面仍然不太懂,在之后的学习中要更加努力,课后要多练习,尤其是关于本章节的泛型的使用等各个方面,也希望老师能更加详细的讲解。

201871010101-陈来弟《面向对象程序设计(Java)》第十一周学习总结的更多相关文章

  1. 201771010134杨其菊《面向对象程序设计java》第九周学习总结

                                                                      第九周学习总结 第一部分:理论知识 异常.断言和调试.日志 1.捕获 ...

  2. 201871010132-张潇潇《面向对象程序设计(java)》第一周学习总结

    面向对象程序设计(Java) 博文正文开头 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cn ...

  3. 扎西平措 201571030332《面向对象程序设计 Java 》第一周学习总结

    <面向对象程序设计(java)>第一周学习总结 正文开头: 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 ...

  4. 杨其菊201771010134《面向对象程序设计Java》第二周学习总结

    第三章 Java基本程序设计结构 第一部分:(理论知识部分) 本章主要学习:基本内容:数据类型:变量:运算符:类型转换,字符串,输入输出,控制流程,大数值以及数组. 1.基本概念: 1)标识符:由字母 ...

  5. 201871010124 王生涛《面向对象程序设计JAVA》第一周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://edu.cnblogs.com/campus/xbsf/ ...

  6. 201871010115——马北《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  7. 201777010217-金云馨《面向对象程序设计(Java)》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  8. 201871010132——张潇潇《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  9. 201771010123汪慧和《面向对象程序设计Java》第二周学习总结

    一.理论知识部分 1.标识符由字母.下划线.美元符号和数字组成, 且第一个符号不能为数字.标识符可用作: 类名.变量名.方法名.数组名.文件名等.第二部分:理论知识学习部分 2.关键字就是Java语言 ...

  10. 20172325 2017-2018-2 《Java程序设计》第十一周学习总结

    20172325 2017-2018-2 <Java程序设计>第十一周学习总结 教材学习内容总结 Android简介 Android操作系统是一种多用户的Linux系统,每个应用程序作为单 ...

随机推荐

  1. destoon模块绑定二级域名出现 File not found解决办法

    昨天晚上帮一个朋友给我说他绑定模块二级域名出现 File not found,所以今天分享关于解决办法. 模块启用二级域名后,首页打开正常,但是点内容页和列表页出现File not found. 解决 ...

  2. C++ 模板特化、偏特化测试程序

    #include <iostream> // 偏特化的模板不会自己添加构造函数 ctor 和 析构函数 dtor #if 1 // P1 template <typename T1, ...

  3. Spring Boot 自定义Intercepter

    在 SpringBoot2.X 中 ,WebMvcConfigurerAdapter 被deprecated , 更好的做法是 implements WebMvcConfigurer 一.自定义拦截器 ...

  4. 剑指Offer-8.跳台阶(C++/Java)

    题目: 一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果). 分析: 实际上就是斐波那契数列的一个应用,青蛙跳上n级台阶的跳法数等于跳 ...

  5. 快速获取 IP 地址

    IP 地址可以分为两类,公用和私有(专用).公用 IP 是唯一的 IP 地址,可以从 Internet 访问.专用 IP 地址保留供您专用网络内部使用,而不会直接暴露给 Internet. 本文将介绍 ...

  6. React内容

    React Fiber   16版本 registerServiceWorker 的作用 PWA  progressive web application  写手机app应用   在断网的情况下,第二 ...

  7. 如何编写一个 SendFile 服务器

    如何编写一个 SendFile 服务器 前言 之前讨论零拷贝的时候,我们知道,两台机器之间传输文件,最快的方式就是 send file,众所周知,在 Java 中,该技术对应的则是 FileChann ...

  8. JSP页面的注释细节

    业务场景:通过后台传参,jstl标签控制一个页签是否显示,不过现在要去掉判断,直接让页签显示 在sublime直接这样注释,然后刷新,一直找不到标签显示,其它的都是正常的 <!--<c:i ...

  9. windows下mysql安装和配置

    历史版本下载地址安装,解压添加环境变量使用cmd中操作mysql进程修改mysql的配置附录:设置mysql随开机自启 TOC 历史版本下载地址 windows的mysql历史版本,推荐使用5.6版本 ...

  10. SpringBoot整合kafka(实现producer和consumer)

    本文代码使用的是Spring Boot 2.1.8.RELEASE 版本 <parent> <groupId>org.springframework.boot</grou ...