2014-09-23 30 views
0

我创建了一个类来模拟堆栈。现在类型被固定为浮动。我在java util类中看到他们有一个堆类文件可以定义类型。试图在类上创建一个堆栈类whare可以处理不同的数据类型

我找不到任何关于如何创建一个类,其中一个verbol类型可以定义何时创建对象。我试着用谷歌搜索的模板totiol,我想在c中他们称之为模板。

所以我有classpublic类CSTACK {

float data[]; 
int size=0; 
int pes=0; 

cStack(int size) 
{ 
    data=new float[size]; 
    pes=0; 
} 

现在数据是DEF为浮点数,我想它所以当我创建类我可以设置的类型。所以它可以容纳浮点数,或整数或字符串。

+2

谷歌“java泛型”。您还需要了解有关基本包装类的信息,例如。为java.lang.Integer。 – TedTrippin 2014-09-23 15:39:16

回答

0

这是布鲁斯Eckel的“Thinking in Java”通用LinkedStack实现:

public class LinkedStack<T> { 
     private static class Node<U> { 
      U item; 
      Node<U> next; 

      Node() { 
       item = null; 
       next = null; 
      } 

      Node(U item, Node<U> next) { 
       this.item = item; 
       this.next = next; 
      } 

      boolean end() { 
       return item == null && next == null; 
      } 
     } 

     private Node<T> top = new Node<T>(); // End sentinel 

     public void push(T item) { 
      top = new Node<T>(item, top); 
     } 

     public T pop() { 
      T result = top.item; 
      if (!top.end()) 
       top = top.next; 
      return result; 
     } 

     public static void main(String[] args) { 
      LinkedStack<String> lss = new LinkedStack<String>(); 
      for (String s : "Phasers on stun!".split(" ")) 
       lss.push(s); 
      String s; 
      while ((s = lss.pop()) != null) 
       System.out.println(s); 
     } 
    } 

我会建议你阅读整本书,特别是‘仿制药’一章。

相关问题