堆栈泛型类工作不
问题描述:
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))中获得数组声明中的错误。在这两种情况下,错误都是“通用数组创建”。请帮助
答
通用数组无法创建。所以使用Object数组。
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;
}
}
答
你的类没有构造函数,这些都是方法。为construtors删除void类型。构造函数没有返回类型。此外,您的班级名称以低字母堆栈开始,构造函数以堆栈开始。将你的类重命名为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);
}
}
请参阅此问题:http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation – Mat 2012-04-11 12:49:13
你的构造函数是不是真的构造函数,因为构造函数没有返回类型。另外,你正在扩展'Vector',这意味着你不需要有一个本地数组。 – Paaske 2012-04-11 13:05:55