import java.util.EmptyStackException;
import java.util.Vector;
public class Stack<E> extends Vector<E> {
private E a[];
private int top;
public void Stack() {
a = new E[100];
top = -1;
}
public void Stack(int n) {
a = new E[n];
top = -1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
}
这是我在java中的堆栈泛型类。我在两个构造函数中的数组声明中得到一个错误,即Stack()和Stack(int n)。在这两种情况下,错误都是“通用阵列创建”。请帮忙
答案 0 :(得分:1)
您的类中没有构造函数,这些是方法。对于construtors删除void类型。构造函数没有返回类型。您的类名也以较低的字母堆栈开头,构造函数以Stack开头。将您的类重命名为Stack并删除void类型。
你需要这样做
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
以下是您在main方法中创建对象的工作类。
class Stack<E> extends Vector<E> {
private E a[];
private int top;
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
public static void main(String...strings ){
Stack<Integer> st=new Stack<Integer>(Integer.class,n);
}
}
答案 1 :(得分:1)
无法创建泛型数组。所以使用Object array。
import java.io.*;
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack extends Vector
{
private Object a[];
private int top;
public void Stack()
{
a=new Object[100];
top=-1;
}
public void Stack(int n)
{
a=new Object[n];
top=-1;
}
public E pop()
{
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj=(E) a[top--];
return obj;
}
public void push(E e)
{
if(e==null)
throw new NullPointerException();
else if(top==size()-1)
System.out.println("Stack full");
else
{
a[++top]=e;
System.out.println("pushed :"+e);
}
}
public int size()
{
int i;
for(i=0;a[i]!=null;i++);
return i;
}
}