201871010114-李岩松《面向对象程序设计(java)》第十一周学习总结

项目

内容

这个作业属于哪个课程

https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

https://www.cnblogs.com/nwnu-daizh/p/11435127.html

作业学习目标

  1. 理解泛型概念;
  2. 掌握泛型类的定义与使用;
  3. 掌握泛型方法的声明与使用;
  4. 掌握泛型接口的定义与实现;
  5. 了解泛型程序设计,理解其用途。

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

  1.1  泛型概述

在前面学习集合时,我们都知道集合中是可以存放任意对象的,只要把对象存储集合后,那么这时他们都会被提升成Object类型。当我们在取出每一个对象,并且进行相应的操作,这时必须采用类型转换。

大家观察下面代码:

~~~java
public class GenericDemo {
    public static void main(String[] args) {
        Collection coll = new ArrayList();
        coll.add("abc");
        coll.add("itcast");
        coll.add(5);//由于集合没有做任何限定,任何类型都可以给其中存放
        Iterator it = coll.iterator();
        while(it.hasNext()){
            //需要打印每个字符串的长度,就要把迭代出来的对象转成String类型
            String str = (String) it.next();
            System.out.println(str.length());
        }
    }
}
~~~

程序在运行时发生了问题**java.lang.ClassCastException**。   为什么会发生类型转换异常呢?  我们来分析下:由于集合中什么类型的元素都可以存储。导致取出时强转引发运行时 ClassCastException。   怎么来解决这个问题呢?     Collection虽然可以存储各种对象,但实际上通常Collection只存储同一类型对象。例如都是存储字符串对象。因此在JDK5之后,新增了**泛型**(**Generic**)语法,让你在设计API时可以指定类或方法支持泛型,这样我们使用API的时候也变得更为简洁,并得到了编译时期的语法检查。

**泛型**:可以在类或方法中预支地使用未知的类型。

> tips:一般在创建对象时,将未知的类型确定具体的类型。当没有指定泛型时,默认类型为Object类型。

1.2  使用泛型的好处

上一节只是讲解了泛型的引入,那么泛型带来了哪些好处呢?

将运行时期的ClassCastException,转移到了编译时期变成了编译失败。
避免了类型强转的麻烦。

通过我们如下代码体验一下:

~~~java
public class GenericDemo2 {
    public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("itcast");
        // list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
        // 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
            System.out.println(str.length());
        }
    }
}
~~~

> tips:泛型是数据类型的一部分,我们将类名与泛型合并一起看做数据类型。

1.3  泛型的定义与使用

我们在集合中会大量使用到泛型,这里来完整地学习泛型知识。

泛型,用来灵活地将数据类型应用到不同的类、方法、接口当中。将数据类型作为参数进行传递。

 定义和使用含有泛型的类

定义格式:

~~~
修饰符 class 类名<代表泛型的变量> {  }
~~~

例如,API中的ArrayList集合:

~~~java
class ArrayList<E>{ 
    public boolean add(E e){ }

    public E get(int index){ }
       ....
}
~~~

使用泛型: 即什么时候确定泛型。

**在创建对象的时候确定泛型**

 例如,`ArrayList<String> list = new ArrayList<String>();`

此时,变量E的值就是String类型,那么我们的类型就可以理解为:

~~~java 
class ArrayList<String>{ 
     public boolean add(String e){ }

     public String get(int index){  }
     ...
}
~~~

再例如,`ArrayList<Integer> list = new ArrayList<Integer>();`

此时,变量E的值就是Integer类型,那么我们的类型就可以理解为:

~~~java
class ArrayList<Integer> { 
     public boolean add(Integer e) { }

     public Integer get(int index) {  }
     ...
}
~~~

举例自定义泛型类

~~~java
public class MyGenericClass<MVP> {
    //没有MVP类型,在这里代表 未知的一种数据类型 未来传递什么就是什么类型
    private MVP mvp;
     
    public void setMVP(MVP mvp) {
        this.mvp = mvp;
    }
     
    public MVP getMVP() {
        return mvp;
    }
}
~~~

使用:

~~~java
public class GenericClassDemo {
      public static void main(String[] args) {         
         // 创建一个泛型为String的类
         MyGenericClass<String> my = new MyGenericClass<String>();        
         // 调用setMVP
         my.setMVP("大胡子登登");
         // 调用getMVP
         String mvp = my.getMVP();
         System.out.println(mvp);
         //创建一个泛型为Integer的类
         MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); 
         my2.setMVP(123);         
         Integer mvp2 = my2.getMVP();
    }
}
~~~

  含有泛型的方法

定义格式:

~~~
修饰符 <代表泛型的变量> 返回值类型 方法名(参数){  }
~~~

例如,

~~~java
public class MyGenericMethod {      
    public <MVP> void show(MVP mvp) {
        System.out.println(mvp.getClass());
    }
    
    public <MVP> MVP show2(MVP mvp) {    
        return mvp;
    }
}
~~~

使用格式:**调用方法时,确定泛型的类型**

~~~java
public class GenericMethodDemo {
    public static void main(String[] args) {
        // 创建对象
        MyGenericMethod mm = new MyGenericMethod();
        // 演示看方法提示
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45);
    }
}
~~~

### 含有泛型的接口

定义格式:

~~~
修饰符 interface接口名<代表泛型的变量> {  }
~~~

例如,

~~~java
public interface MyGenericInterface<E>{
    public abstract void add(E e);
    
    public abstract E getE();  
}
~~~

使用格式:

**1、定义类时确定泛型的类型**

例如

~~~java
public class MyImp1 implements MyGenericInterface<String> {
    @Override
    public void add(String e) {
        // 省略...
    }

    @Override
    public String getE() {
        return null;
    }
}
~~~

此时,泛型E的值就是String类型。

 **2、始终不确定泛型的类型,直到创建对象时,确定泛型的类型**

 例如

~~~java
public class MyImp2<E> implements MyGenericInterface<E> {
    @Override
    public void add(E e) {
            // 省略...
    }

    @Override
    public E getE() {
        return null;
    }
}
~~~

确定泛型:

~~~java
/*
 * 使用
 */
public class GenericInterface {
    public static void main(String[] args) {
        MyImp2<String>  my = new MyImp2<String>();  
        my.add("aa");
    }
}
~~~

 1.4  泛型通配符

当使用泛型类或者接口时,传递的数据中,泛型类型不确定,可以通过通配符<?>表示。但是一旦使用泛型的通配符后,只能使用Object类中的共性方法,集合中元素自身方法无法使用。

 通配符基本使用

泛型的通配符:**不知道使用什么类型来接收的时候,此时可以使用?,?表示未知通配符。**

此时只能接受数据,不能往该集合中存储数据。

举个例子大家理解使用即可:

~~~java
public static void main(String[] args) {
    Collection<Intger> list1 = new ArrayList<Integer>();
    getElement(list1);
    Collection<String> list2 = new ArrayList<String>();
    getElement(list2);
}
public static void getElement(Collection<?> coll){}
//?代表可以接收任意类型
~~~

> tips:泛型不存在继承关系 Collection<Object> list = new ArrayList<String>();这种是错误的。

#### 通配符高级使用----受限泛型

之前设置泛型的时候,实际上是可以任意设置的,只要是类就可以设置。但是在JAVA的泛型中可以指定一个泛型的**上限****下限**

**泛型的上限**

**格式**: `类型名称 <? extends 类 > 对象名称`
**意义**: `只能接收该类型及其子类`

**泛型的下限**

**格式**: `类型名称 <? super 类 > 对象名称`
**意义**: `只能接收该类型及其父类型`

比如:现已知Object类,String 类,Number类,Integer类,其中Number是Integer的父类

~~~java
public static void main(String[] args) {
    Collection<Integer> list1 = new ArrayList<Integer>();
    Collection<String> list2 = new ArrayList<String>();
    Collection<Number> list3 = new ArrayList<Number>();
    Collection<Object> list4 = new ArrayList<Object>();
    
    getElement(list1);
    getElement(list2);//报错
    getElement(list3);
    getElement(list4);//报错
  
    getElement2(list1);//报错
    getElement2(list2);//报错
    getElement2(list3);
    getElement2(list4);
  
}
// 泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类
public static void getElement1(Collection<? extends Number> coll){}
// 泛型的下限:此时的泛型?,必须是Number类型或者Number类型的父类
public static void getElement2(Collection<? super Number> coll){}
~~~

第二部分:实验部分

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

测试程序1:

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

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

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

/**
 * @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)//实例化的一个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++)
      {
         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> 
{
   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:

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

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

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

package pair2;

import java.time.*;

/**
 * @version 1.02 2015-06-21
 * @author Cay Horstmann
 */
public class PairTest2
{
   public static void main(String[] args)
   {
       //初始化LocalDate对象数组
      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);//通过类名调用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)//通过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:

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

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

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);      
      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)//通配符类型(带有上界)extends关键字所声明的上界既可以是一个类,也可以是一个接口。
   {
      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)//通配符类型(带有下界)必须是Manager的子类
   {
      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); //swapHelper捕获通配符类型
   }
   //无法编写公共静态< T超级管理器>
}

class PairAlg
{
   public static boolean hasNulls(Pair<?> p)//通过将hasNulls转换成泛型方法,避免使用通配符类型
   {
      return p.getFirst() == null || p.getSecond() == null;
   }

   public static void swap(Pair<?> p) { swapHelper(p); }

   public static <T> void swapHelper(Pair<T> p)//使用辅助方法swapHelper(泛型方法),以在交换时临时保存第一个元素
   {
      T t = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(t);
   }
public class Pair<T> 
{
   private T first;
   private T second;
//T是未知类型,不代表值
   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; }
}
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;
   }
}
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:结对编程练习

实验2结对编程练习,将程序提交到PTA2019面向对象程序设计基础知识测试题(2))

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

push(item);            //itemnull,则不入栈直接返回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,程序直接退出。否则,输入整数mnm代表入栈个数,n代表出栈个数。然后声明栈变量stack

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

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

ü  输入Car,打印Car Test。其他操作与IntegerDouble基本一样。只不过最后将栈中元素出栈,并将其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

结对编程合作对象胡欢欢

 结对编程实验代码:

 GeneralStack接口:
package week111;

public interface GeneralStack<T> {
   public T push(T item);//判断栈是否为空
   public T pop();//出栈,如果栈为空则返回null
   public T peek();//获得栈顶元素,如果为空,则返回null
   public boolean empty();//如为空返回true
   public int size();     //返回栈中元素数量
}
/*car类*/
package
week111; public class Car { private int id; private String name; public String toString() { return "Car ["+"id="+id+",name="+name+']'; } public int getId() { return id; } public void setId() { 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; } }
/*ArrayListGeneralStack类*/
package
week111; import java.util.ArrayList; public class ArrayListGeneralStack<E> implements GeneralStack { ArrayList list=new ArrayList<E>(); public String toString() { return list.toString(); } @Override public Object push(Object item) { // TODO Auto-generated method stub if(list.add(item)) { return item; } else { return false; } } @Override public Object pop() { // TODO Auto-generated method stub if(list.size()==0) { return null; } return list.remove(list.size()-1); } @Override public Object peek() { // TODO Auto-generated method stub return list.get(list.size()-1); } @Override public boolean empty() { // TODO Auto-generated method stub if(list.size()==0) { return true; }else { return false; } } @Override public int size() { // TODO Auto-generated method stub return list.size(); } }
/*Main类*/
package
week111; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(true) { String s=sc.next(); if(s.equals("Double")) { System.out.println("Double Test"); int count=sc.nextInt(); int pop_time=sc.nextInt(); ArrayListGeneralStack generalStack=new ArrayListGeneralStack(); for(int i=0;i<count;i++) { System.out.println("push:"+generalStack.push(sc.nextDouble())); } for(int j=0;j<pop_time;j++) { System.out.println("pop:"+generalStack.pop()); } System.out.println(generalStack.toString()); double sum=0; int size=generalStack.size(); for(int i=0;i<size;i++) { sum+=(double)generalStack.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 generalStack=new ArrayListGeneralStack(); for(int i=0;i<count;i++) { System.out.println("push:"+generalStack.push(sc.nextInt())); } for(int j=0;j<pop_time;j++) { System.out.println("pop:"+generalStack.pop()); } System.out.println(generalStack.toString()); int sum=0; int size=generalStack.size(); for(int i=0;i<size;i++) { sum+=(int)generalStack.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 generalStack = new 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:"+generalStack.push(car)); } for (int i=0;i<pop_time;i++){ System.out.println("pop:"+generalStack.pop()); } System.out.println(generalStack.toString()); if (generalStack.size()>0){ int size=generalStack.size(); for (int i=0;i<size;i++){ Car car=(Car) generalStack.pop(); System.out.println(car.getName()); } } System.out.println("interface GeneralStack"); }else if (s.equals("quit")){ break; } } } }

 运行结果:

 

 

实验总结:

1 泛型的概念定义:

         i.引入了参数化类型(Parameterized Type)的概念,改造了所有的Java集合,使之都实现泛型,允许程序在创建集合时就可以指定集合元素的类型,比如List<String>就表名这是一个只能存放String类型的List;

         ii. 泛型(Generic):就是指参数化类型,上面的List<String>就是参数化类型,因此就是泛型,而String就是该List<String>泛型的类型参数;

    3) 泛型的好处:

         i. 使集合可以记住元素类型,即取出元素的时候无需进行强制类型转化了,可以直接用原类型的引用接收;

         ii. 一旦指定了性参数那么集合中元素的类型就确定了,不能添加其他类型的元素,否则会直接编译保存,这就可以避免了“不小心放入其他类型元素”的可能;

 2,通配符

1.)在实例化对象的时候,不确定泛型参数的具体类型时,可以使用通配符进行对象定义。

2)<? extends Object>代表上边界限定通配符

3) <? super Object>代表下边界限定通配符。

感受:

通过本周的学习,掌握了泛型类的定义,以及泛型方法的声明,还有泛型接口的定义,以及对泛型变量的限定。

在本周结对编程训练时,还是有很大问题,这样的分工合作确实效率很大程度上增加,但是由于语法掌握还不是很牢靠,仍旧需要大量适度练习,在之后的学习中,我会多练习程序去了解这些知识,争取能够独立完整的去编写程序。

posted @ 2019-11-11 21:25  小高家的小胖子  阅读(184)  评论(1编辑  收藏  举报