我是Java中的Generics的新手,我真的需要这段代码的帮助
它不编译我不知道为什么!
堆栈类是:
public class GenericStack<Item>{
public class Stack {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
}
这是主要的
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericStack<Integer> ob = new GenericStack<Integer>();
ob.push(5);
obpush(10);
ob.push(15);
while (!ob.IsEmpty())
{
int x=ob.pop();
StdOut.print(x);
}
}
}
现在错误是:
The method push(int) isn't defined for the type GenericStack<Integer>
我哪里出错?!任何人都可以向我解释
提前谢谢
答案 0 :(得分:3)
您的GenericStack
班级没有方法。摆脱嵌套的类结构并直接使用Stack
的泛型类型参数:
public class Stack<Item> {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
答案 1 :(得分:2)
因为方法push
是在课程GenericStack.Stack
中定义的,而不是GenericStack
。为了使它工作替换
GenericStack<Integer> ob = new GenericStack<Integer> ();
带
GenericStack<Integer>.Stack ob = new GenericStack.Stack ();
答案 2 :(得分:2)
您的代码的主要问题是您混合了2个公共类,只需更改一些代码,玩得开心!!
GenericStack.java
public class GenericStack<Item> {
private Node first = null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty() {
return first == null;
}
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop() {
Item item = first.item;
first = first.next;
return item;
}
}
TestGenericStack.java
public class TestGenericStack {
public static void main(String[] args) {
GenericStack<Integer> ob = new GenericStack<Integer>();
ob.push(5);
ob.push(10);
ob.push(15);
while (!ob.IsEmpty()) {
int x = ob.pop();
System.out.println(x);
}
}
}
答案 3 :(得分:2)
class GenericStack<Item>{
class Stack {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericStack<Integer> ob = new GenericStack<Integer>();
GenericStack<Integer>.Stack st=ob.new Stack();
st.push(5);
st.push(10);
st.push(15);
while (!st.IsEmpty())
{
int x=st.pop();
// StdOut.print(x);
System.out.println(x);
}
}
}
您正在调用内部类的方法。因此,使用外部类的对象不能直接调用内部类的方法。请参阅上面的代码。
希望这有帮助。
答案 4 :(得分:1)
从Stack
中删除额外的GenericStack
课程。
谢谢!