201871010107-公海瑜《面向对象程序设计(java)》第十一周学习总结

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

1.理解泛型概念;

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

3.掌握泛型方法的声明与使用;

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

5.了解泛型程序设计,理解其用途。

第一部分:总结第八章关于泛型程序设计理论知识

1.泛型:参数化类型,在定义类、接口、方法时通过类型参数指示将要处理的对象类型

2.泛型程序设计意味着编写的代码可以被许多不同类型的对象所重用

3.定义简单泛型类:

  (1)一个泛型类就是具有一个或多个类型变量的类,即创建用类型作为参数的类

  (2)以Pair类为例:public class Pair<T>

             {

......

              }

    Pair类引入了一个类型变量T,用尖括号(<>)括起来,并放在类名的后面

  (3)泛型类可以有多个类型变量。例如,可以定义Pair类,其中第一个域和第二个域使用不同的类型:public class Pair<T,U> { ... }

  (4)类定义中的类型变量指定方法的返回类型以及域和局部变量的类型

  (5)实例化泛型对象时,一定要在类名后面指定类型参数的值,一共要有两次书写,例如:TestGeneric<String,String> t=new TestGeneric<String,String>();

4.泛型方法:

  (1)定义泛型方法时注意,类型变量放在修饰符(public static)的后面,返回类型的前面

  (2)泛型方法可以定义在普通类中,也可以定义在泛型类中

  (3)当调用一个泛型方法时,在方法名前的尖括号中放入具体的类型

5.泛型接口的定义与实现:

  (1)定义:public interface IPool<T>

{

         T get();

            int add(T t);

}

  (2)实现:public class GenericPool<T> implements IPool<T> { ... }

         public class GenericPool implements IPool<Account> { ... }

6.类型变量的限定:

  (1)定义泛型变量的上界(用extends)

    <T extends BoundingType>表示T是绑定类型的子类型。T和绑定类型可以是类,也可以是接口

    一个类型变量或通配符可以有多个限定,例如:T extends Comparable & Serializable(限定类型用“&”分隔)

  (2)定义泛型变量的下界(用super)     例如:<? super T>

7.泛型类的约束与局限:

  (1)不能用基本类型实例化类型参数

  (2)运行时类型查询只适用于原始类型

  (3)不能抛出也不能捕获泛型类实例

  (4)参数化类型的数组不合法

  (5)不能实例化类型变量

  (6)泛型类的静态上下文中类型变量无效

  (7)注意擦除后的冲突

8.泛型类型的继承规则:Java中的数组是协变的,但泛型类不是协变的

9.通配符类型:(?,任何类型;T , 某一种类型)

  (1)单独的?,用于表示任何类型

  (2)?extends type,表示带有上界

  (3)? super type,表示带有下界

10.(1)通配符的类型限定: Pair<? extends Employee>

             Pair<? super Manager>

 (2)无限定通配符:Pair<?>(Pair<?>与Pair的不同在于:可以用任意Object对象调用原始的Pair类的setObject方法)

第二部分:实验部分

实验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" };
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 values, or null if a is null or empty
*/
public static Pair<String> minmax(String[] a) //使用泛型Pair类
{
if (a == null || a.length == ) return null;
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);
}
}
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; }
}

运行结果:

测试程序2:

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

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

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

代码如下:

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);
//在Pair中定义一个LocalDate类的birthdays数组
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
} class ArrayAlg //泛型类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)
//使用extends关键字,定义泛型变量的上界,调用Comparable接口
{
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);
}
}
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; }
}

运行结果:

测试程序3:

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

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

代码如下:

package pair3;

/**
* @version 1.01 2012-01-26
* @author Cay Horstmann
*/
public class PairTest3
{
public static void main(String[] args)
{
var ceo = new Manager("Gus Greedy", , , , );
var cfo = new Manager("Sid Sneaky", , , , );
var buddies = new Pair<Manager>(ceo, cfo);
printBuddies(buddies); ceo.setBonus();
cfo.setBonus();
Manager[] managers = { ceo, cfo }; var result = new Pair<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 == ) 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)
{
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;

/**
* @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 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;
}
}
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;
}
}

实验结果如图:

实验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方法。

(4)main方法要求

ü 输入选项,有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(); //返回栈中元素数量
}
class ArrayListGeneralStack implements GeneralStack{ //泛型接口GeneralStack
ArrayList list=new ArrayList();
@Override
public String toString() {
return list.toString();
} @Override
public Object push(Object item) {//入栈
if (list.add(item)){
return item;
}else {
return false;
}
} @Override
public Object pop() {//出栈
if (list.size()==){
return null;
}
return list.remove(list.size()-);
} @Override
public Object peek() { //取栈顶元素
return list.get(list.size()-);
} @Override
public boolean empty() {
if (list.size()==){
return true;
}else {
return false;
}
} @Override
public int size() {
return list.size();
}
} class Car{ //Car类
private int id;
private String name; @Override
public String toString() { //Eclipse自动生成setter/getter,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) {
@SuppressWarnings("resource")
Scanner in=new Scanner(System.in);
while (true){
String s=in.nextLine();
if (s.equals("Integer"))//为Integer
{
int count=in.nextInt();
int pop_time=in.nextInt();
System.out.println("Integer Test");
ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
for (int i=;i<count;i++){
System.out.println("push:"+arrayListGeneralStack.push(in.nextInt()));
}
for (int i=;i<pop_time;i++){
System.out.println("pop:"+arrayListGeneralStack.pop());
}
System.out.println(arrayListGeneralStack.toString());
int size=arrayListGeneralStack.size();
int sum=;
for (int i=;i<size;i++){
sum=sum+(int)(arrayListGeneralStack.pop());
}
System.out.println("sum="+sum);
System.out.println("interface GeneralStack");
}else if(s.equals("Double"))//为Double
{
System.out.println("Double Test");
int count=in.nextInt();
int pop_time=in.nextInt();
ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
for (int i=;i<count;i++)
{
System.out.println("push:"+arrayListGeneralStack.push(in.nextDouble()));
}
for (int i=;i<pop_time;i++)
{
System.out.println("pop:"+arrayListGeneralStack.pop());
}
System.out.println(arrayListGeneralStack.toString());
int size=arrayListGeneralStack.size();
double sum=;
for (int i=;i < size;i++){
sum = sum + (double)(arrayListGeneralStack.pop());
}
System.out.println("sum="+sum);
System.out.println("interface GeneralStack");
}else if (s.equals("Car"))
{
System.out.println("Car Test");
int count=in.nextInt();
int pop_time=in.nextInt();
ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
for (int i=;i<count;i++)
{
int id=in.nextInt();
String name=in.next();
Car car = new Car(id,name);
System.out.println("push:"+arrayListGeneralStack.push(car));
}
for (int i=;i<pop_time;i++)
{
System.out.println("pop:"+arrayListGeneralStack.pop());
}
System.out.println(arrayListGeneralStack.toString());
if (arrayListGeneralStack.size()>)
{
int size=arrayListGeneralStack.size();
for (int i=;i<size;i++)
{
Car car=(Car) arrayListGeneralStack.pop();
System.out.println(car.getName());
}
}
System.out.println("interface GeneralStack");
}else if (s.equals("quit"))
{
break;
}
} }
}

运行结果如图:

实验总结:

通过本周的学习,我对java的面向对象程序设计有了更深的理解,对泛型、泛型类的定义与使用、泛型方法的实现都有了基础的操作方法,也学习到了通配符的基本使用规则,对java整体上也有了更深层次的认识与掌握,继续加油。

//使用泛型Pair类

最新文章

  1. 【Android】Android如何一进入一个activity就弹出输入法键盘
  2. Linux下安装mysql数据库
  3. MPICH3 配置安装问题列表
  4. ASP.NET一些公共方法commTools
  5. VBA中四种自动运行的宏以及模块的含义
  6. AOP面向切面编程
  7. 【转】Android Drawable Resource学习(十一)、RotateDrawable
  8. centos7 搭建docker内运行rabbitmq,然后再镜像ha方案的完全教程,暂时一个宿主机只能运行一个docker的rabbitmq,但是集群 ha都正常
  9. Data binding 在Activity,Fragment中引用以及加载其他布局
  10. 解决:javah 无法访问引用Android对象的问题
  11. CSS中常见的BUG调试
  12. 组队赛第二场:字符串哈希+DP
  13. 关于Python的文件IO
  14. GDB调试指南-变量查看
  15. 论文笔记:ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware
  16. Ibatis中的&lt;trim&gt;标签应用
  17. CTF-练习平台-Misc之 这是一张单纯的图片??
  18. 2018.07.07 洛谷 P3939 数颜色(主席树)
  19. kNN--近邻算法
  20. 《Maven实战》第5章 坐标和依赖

热门文章

  1. CF92B-Binary Number-(思维)
  2. go 通过select实现超时
  3. 舒服的MarkDown软件Mark Text
  4. node启动服务后,窗口不能关闭。pm2了解一下
  5. QPushButton 一组中凸显选中的一个,且只能选中一个。
  6. webrtc笔记(2): 1对1实时视频/语音通讯原理概述
  7. 【12月13日】A股ROE最高排名
  8. 小小见解之python循环依赖
  9. iview 组件的额外传参问题记录
  10. iOS 一个项目添加多个TARGET