201871010102-常龍龍《面向對象程序設計(java)》第十一週學習總結

項目html

內容java

這個做業屬於哪一個課程編程

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

這個做業的要求在哪裏安全

https://www.cnblogs.com/nwnu-daizh/p/11815810.htmlide

做業學習目標函數

     

                                  

              (1) 理解泛型概念;學習

              (2) 掌握泛型類的定義與使用;測試

              (3) 瞭解泛型方法的聲明與使用;ui

              (4) 掌握泛型接口的定義與實現;

              (5) 理解泛型程序設計,理解其用途。

 

第一部分:總結第八章關於泛型程序設計理論知識(25分)

 1、泛型類的定義
●一個泛型類(generic class) 就是具備一個或多個類型變量的類,即建立用類型做爲參數的類。

          如一個泛型類定義格式以下:class Generics <K,V>
          其中K和V是類的可變類型參數。

2、泛型方法
          1.除了泛型類外,還能夠只單獨定義一個方法做爲泛型方法,用於指定方法參數或者返回值爲泛型類型,留待方法調用時肯定。
          2.泛型方法能夠聲明在泛型類中,也能夠聲明在普通類中。
3、泛型接口的定義
●定義
public interface IPool <T>{
           T get();
           int add(T t); 
}
●實現
public class GenericPool <T> implements IPool<T>
{

.....

}
public class GenericPool implements IPool< Account>

{

.....

}

4、泛型變量的限定

1. 定義泛型變量的 上界
public class NumberGeneric< T extends Number>

■泛型變量上界的說明

       ◆上述聲明規定了NumberGeneric類所能處理的泛型變量類型需和Number有繼承關係; 
       ◆extends關鍵字所聲明的上界既能夠是一一個類,也能夠是一一個接口;

●<T extends Bounding Type>表示T應該是綁定類型的子類型。
●一個類型變量或通配符能夠有多個限定,限定類型用「&」分割。例如:
           < T extends Comparable & Serlallzable >

2. 定義泛型變量的 上界

■泛型變量下界的說明
        ◆經過使用super關鍵字能夠固定泛型參數的類型爲某種類型的超類
        ◆當但願爲一個方法的參數限定類型時,一般可使用下限通配符
public static <T> void sort(T[] a,Comparator<? super T> c)

通配符類型
●通配符
     「?」代表參數類型能夠是任何一種類型,通配符-般有如下三種用法:
             1.單獨的?,用於表示任何類型。

             2.? extends type, 表示帶有上界。

             3.? super type,表示帶有下界。

5、泛型程序設計小結
●定義一個泛型類時,在「<>」內定義形式類型參數,例如:「class TestGeneric<K, V>」,其中「K」,「V」不表明值,而是表示類型。
●實例化泛型對象的時候,- 定要在類名後面指定類型參數的值(類型),-共要有兩次書寫。
        例如:TestGeneric<String, String> t
                                   =new TestGeneric <String, String> ();

●泛型中<T extends Object> , extends並不表明繼承,它是類型範圍限制。

●泛型類不是協變的。

第二部分:實驗部分

實驗1 導入第8章示例程序,測試程序並進行代碼註釋。

測試程序1:

● 編輯、調試、運行教材311312頁代碼,結合程序運行結果理解程序;

● 在泛型類定義及使用代碼處添加註釋;

● 掌握泛型類的定義及使用。 

代碼以下:

1.Pair類:

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.PairTest1類:

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" };
      //向ArrayAlg類的minmax方法中傳入一個字符串數組
      //將返回的Pair泛型對象傳給Pair泛型變量
      Pair<String> mm = ArrayAlg.minmax(words);
      //經過mm調用它的方法
      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)
   {
      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];
      }
      //找出字符串數組中的最大最小值後,把兩個值做爲產生Pair泛型的對象的構造方法參數傳入
      //建立對象後並返回
      return new Pair<>(min, max);
   }
}

運行結果以下:

 

 

測試程序2:

● 編輯、調試運行教材315 PairTest2,結合程序運行結果理解程序;

● 在泛型程序設計代碼處添加相關注釋;

● 瞭解泛型方法、泛型變量限定的定義及用途。

代碼以下:

1.Pair類

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; }
}

2.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[] 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
         };
      System.out.println("----------------");
      Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg
{
   /**
            獲取T類型對象數組的最小值和最大值。
      @param 一個T類型的對象數組
      @return 具備最小值和最大值的對,若是a爲null或空,則爲null
   */
   public static <T extends Comparable> Pair<T> minmax(T[] a) 
   //對類型變量進行限定,T限制爲實現了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++)
      {
         //實現了Comparable類的的數組可使用compareTo()方法
         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,結合程序運行結果理解程序;

● 瞭解通配符類型的定義及用途。

代碼以下:

1.Employee類

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;
   }
}

2.Manager類

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;
   }
}

3.pair類

 

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; }
}

4.PairTest3類

package pair3;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest3
{
   public static void main(String[] args)
   {
       //建立了兩個Manager類對象
      Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
      Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
      //將兩個Manager類對象做爲參數傳入到Pair泛型類的構造方法中
      Pair<Manager> buddies = new Pair<Manager>(ceo, cfo);
      //將兩個對象做爲參數傳入靜態方法printBuddies,調用兩個對象的方法,並打印
      printBuddies(buddies);

      ceo.setBonus(1000000);
      cfo.setBonus(500000);
      
      Manager[] managers = { ceo, cfo };

      Pair<Employee> result = new Pair<Employee>();
      
      //找出managers數組中獎金最小和最大的而且做爲參數賦給result的set方法
      minmaxBonus(managers, result); 
      
      //result.getFirst()表明對象
      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)
   {
      //找出a數組中bonus最小的對象和bonus最大的對象
      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泛型的setsetFirst和setSecond方法
      result.setFirst(min);
      result.setSecond(max);
   }

   public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
   {
      minmaxBonus(a, result);
      //調用swapHelper方法將result泛型中的First中保存的最小對象改成最大對象
      PairAlg.swapHelper(result); //OK——swapHelper捕獲通配符類型
   }
   // 沒法編寫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 temp = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(temp);
   }
}

運行結果以下:

 

實驗2:結對編程練習(32分)

 

1 編寫一個泛型接口GeneralStack要求類方法對任何引用類型數據都適用。GeneralStack接口中方法以下:

push(item);            //如item爲null,則不入棧直接返回null。
pop();                 //出棧,如爲棧爲空,則返回null。
peek();                //得到棧頂元素,如爲空,則返回null.
public boolean empty();//如爲空返回true
public int size();     //返回棧中元素數量

2定義GeneralStackArrayListGeneralStack要求:

ü 類內使用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

代碼以下:

 1.General類

package work;

interface GeneralStack<T> {
     public T push(T item);
     public T pop();
     public T peek();
     public boolean empty();
     public int size(); 
}

2.ArrayListGeneralStack類

package work;

import java.util.ArrayList;

class ArrayListGeneralStack implements GeneralStack<Object>{
    ArrayList<Object> list=new ArrayList<>();
    
    @Override
    public  Object push(Object item) {
        if(item!=null)
        {
            list.add(item);
            return item;
        }else {
            return null;
        }
    }


    @Override
    public Object pop() {
        if(list.size()==0)
        {
            return null;
        }else {
            return list.remove(list.size()-1);
        } 
        
    }

    @Override
    public Object peek() {
        if(list.size()==0)
        {
            return null;
        }else {
            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();
    }
     
    public String toString()
    {
        return  list.toString();
    }
}

3.Car類

package work;

public class Car {
    private int id;
    private String name;
    
    public Car(int id, String name) {
        this.id = id;
        this.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;
    }

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

4.Main類

package work;

import java.util.Scanner;

public class Main {
  
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        System.out.println("請輸入選項:"+"\n"+"1.quit"+"\n"+"2.Integer"+"\n"+"3.Double"+"\n"+"4.Car");
        System.out.println("-------------------");
        while(true)
        {
            String choice=in.next();
            if(choice.equals("quit")){
                System.out.println("程序終止");
                break;
            }
            else if(choice.equals("Integer"))
            {
                System.out.println("Integer Test");
                int pushStackTimes=in.nextInt();
                int popStackTimes=in.nextInt();
                ArrayListGeneralStack Stack = new ArrayListGeneralStack();
                for(int i=0;i<pushStackTimes;i++)
                {
                    //System.out.print("push:");
                    System.out.println("push:"+Stack.push(in.nextInt()));
                    //Stack.push(in.nextInt());
                }
                for(int j=0;j<popStackTimes;j++)
                {
                    System.out.println("pop:"+Stack.pop());
                }
                System.out.println(Stack.toString());
                
                Integer sum=0;
                int size=Stack.size();
                for(int k=0;k<size;k++)
                {    
                    sum+=(Integer)Stack.pop();
                }
                System.out.println("sum="+sum); 
                
                //打印接口
                System.out.println(Stack.getClass().getInterfaces()[0]);                                 
            }
            else if(choice.equals("Double"))
            {
                System.out.println("Double Test");
                int pushStackTimes=in.nextInt();
                int popStackTimes=in.nextInt();
                ArrayListGeneralStack Stack = new ArrayListGeneralStack();
                for(int i=0;i<pushStackTimes;i++)
                {
                    //System.out.print("push:");
                    System.out.println("push:"+Stack.push(in.nextDouble()));
                    //Stack.push(in.nextDouble());
                }
                for(int j=0;j<popStackTimes;j++)
                {
                    System.out.println("pop:"+Stack.pop());
                }
                System.out.println(Stack.toString());
                
                Double sum=0.0d;
                int size=Stack.size();
                for(int k=0;k<size;k++)
                {    
                    sum+=(Double)Stack.pop();
                }
                System.out.println("sum="+sum); 
                
                //打印接口
                System.out.println(Stack.getClass().getInterfaces()[0]);                
            }
            else if(choice.equals("Car"))
            {
                System.out.println("Car Test");
                int pushStackTimes=in.nextInt();
                int popStackTimes=in.nextInt();
                ArrayListGeneralStack Stack = new ArrayListGeneralStack();
                for(int i=0;i<pushStackTimes;i++)
                {
                    int id=in.nextInt();
                    String name=in.next();
                    Car car=new Car(id,name);
                    //System.out.print("push:");
                    System.out.println("push:"+Stack.push(car));
                    //Stack.push(car);
                }
                for(int j=0;j<popStackTimes;j++)
                {
                    System.out.println("pop:"+Stack.pop());
                }
                System.out.println(Stack.toString());
                
                //打印剩餘元素的name
                int size=Stack.size();
                for(int k=0;k<size;k++)
                {    
                    Car car=(Car)Stack.pop();
                    System.out.println(car.getName());
                }
                
                //打印接口
                System.out.println(Stack.getClass().getInterfaces()[0]);                
            }
       }
       in.close();
    }
}

 

5.運行結果以下:

 

 

 

 3、實驗總結

這周的知識比較難理解,是一個難點。經過幾個測試程序,我基本上理解而且掌握了泛型的定義,以及泛型類、泛型方法以及泛型接口的使用。本次實驗的編程練習的難度對我來講有點大,讓我以爲我對泛型接口的掌握還不是很到位,最後的代碼結果我是理解了網上的博客以後本身寫的,雖然到如今對它的領悟還不是很深入,但我相信經過對成熟代碼的理解以及平時不斷地編程練習,之後總會在經驗中找出掌握它的屬於個人獨有方法。

相關文章
相關標籤/搜索