在之前的堆栈中,我们只能存储int数据,如果需要存储float数据,就必须再定义一个堆栈。我们发现代码基本上是一样的,只是将其中的部分int改成了float,但是我们不得不重新写一遍。

如果以后还要存储double、String……等类型数据怎么办?有没有一劳永逸的办法只写一遍呢?——泛型。


public class FloatStack {
   private float []data;//数据存储区
   
private int capacity;//堆栈容量
   
private int size;//堆栈当前实际大小
   
private int top;//栈顶位置

   
public FloatStack(int capacity){
      this.capacity = capacity;
      data = new float[capacity];
      size = 0;
      top = -1;
   }

   public boolean isFull(){
      return size == capacity;
   }
   
   public boolean isEmpty(){
      return size == 0;
   }
   
   public boolean push(float d){
      if(isFull()){
         return false;
      }
      
      top++;
      size++;
      data[top] = d;
      
      return true;
   }
   
   public Float pop(){
      if(isEmpty()){
         return null;
      }
      float d = data[top];
      top--;
      size--;
      
      return d;
   }
}


使用泛型定义一个通用性堆栈。也就是把刚才的特定类型改为“某种”类型,即泛指某种类型(这就是泛型的由来)。就这么一点小小的改动带来的确实本质性的变化——一劳永逸,体现了通用。

public class CommonStack<T> {
   private T []data;//数据存储区
   
private int capacity;//堆栈容量
   
private int size;//堆栈当前实际大小
   
private int top;//栈顶位置

   
public CommonStack(int capacity){
      this.capacity = capacity;
      data = (T[]) new Object[capacity];
      size = 0;
      top = -1;
   }

   public boolean isFull(){
      return size == capacity;
   }
   
   public boolean isEmpty(){
      return size == 0;
   }
   
   public boolean push(T d){
      if(isFull()){
         return false;
      }
      
      top++;
      size++;
      data[top] = d;
      
      return true;
   }
   
   public T pop(){
      if(isEmpty()){
         return null;
      }
      T d = data[top];
      top--;
      size--;
      
      return d;
   }
}

 

使用泛型的时候需要指定具体类型

CommonStack<Float>  s2 = new CommonStack<Float> (5);

这个叫类型参数化,也就是将类型作为参数。在此之前我们说的参数都是数据,只不过数据是有类型的。普通参数用“()”,类型参数用“<>”。




简单来说:就是例如堆栈你想要写不同的数据数组,必须要声明不同的类类实现各个数据类型,  但是运用泛型,就是为了只写一个类,在运行的时候 只需要把声明的泛型类型旁边写上你想要实现的类型即可.

,泛型 的详细理解

相关文章:

  • 2022-12-23
  • 2021-11-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-21
  • 2022-03-09
  • 2021-08-28
  • 2022-12-23
相关资源
相似解决方案