0
#include <cstdlib>
#include<iostream>
using namespace std;
template <typename T>
class stack
{
  public:
  T arr[100];
  int top;
  stack()
  {
    top=-1;
  }
  public:
  void push(T x)
  {
    if(top==99)
        cout<<"overflow";
    else
        arr[++top]=x;
  }
  public :
  T pop(void)
  {
    if(top==-1)
        return 0;
    else
        return arr[top--];
  }

};
int main(int argc, char** argv) 
{
  stack <int> s;
  int x;
  cout<<"\nEnter no : ";
  cin>>x;
  s.push(x);
  x=s.pop();
  cout<<"Element popped : "<<x;
  return 0;
 }

这是我的可变数据类型堆栈类的 C++ 代码。它做pop、push的基本功能。我想将此代码转换为 java generics 。因为我对 java 泛型不是很熟悉。请帮我

4

1 回答 1

0


import java.util.EmptyStackException;
import java.util.Vector;

public class Stack extends Vector{

 /**
 * Creates an empty Stack.
 */
public Stack() {

}


public E pop() {
    E   obj;
    int len = size();

    if (len == 0)
        throw new EmptyStackException();
    obj = elementAt(len - 1);
    removeElementAt(len - 1);
    return obj;
}


public void push(E e) {

    if(e==null)
        throw new NullPointerException();
    addElement(e);

}


public int size() {
    return elementCount;
}


public static void main(String args[]){


Stack<Integer>  integerStack= new Stack<Integer>();

//(7,1,3,3,5,1,2,4,3)
integerStack.push(7);
integerStack.push(1);
integerStack.push(3);
integerStack.push(3);
integerStack.push(5);
integerStack.push(1);
integerStack.push(2);
integerStack.push(4);
integerStack.push(3);


System.out.println("STACK WITH INTEGER ELEMENTS");
//Size
System.out.println("Size of the Stack is : "+integerStack.size());



// String Stack
Stack<String>  stringStack= new Stack<String>();

//("abc","def","acd","fgi","fth","lmn","zxy","cde","adr")
stringStack.push("abc");
stringStack.push("def");
stringStack.push("acd");
stringStack.push("fgi");
stringStack.push("fth");
stringStack.push("lmn");
stringStack.push("zxy");
stringStack.push("cde");
stringStack.push("adr");


System.out.println("STACK WITH STRING ELEMENTS");
//Size
System.out.println("Size of the Stack is : "+stringStack.size());



//pop
stringStack.pop();

//Size after pop
System.out.println("Size of the Stack After pop is : "+stringStack.size());

}

}

于 2012-04-11T08:07:57.527 回答