gpt4 book ai didi

java - 堆栈泛型类不起作用

转载 作者:行者123 更新时间:2023-12-02 07:52:09 25 4
gpt4 key购买 nike

Possible Duplicate:
Java how to: Generic Array creation

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))内的数组声明中遇到错误。在这两种情况下,错误都是“通用数组创建”。请帮忙

最佳答案

无法创建通用数组。所以使用对象数组。


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;
}
}

关于java - 堆栈泛型类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com