泛型栈遍历方法错误

Errors with traversal method of generic stack

我在使用以下方法时遇到问题:public void traverseGStack() 带有 print 的行由于某种原因给我一个错误。在 class 中,我们像我写的那样做了,但我认为问题可能出在 E obj = (E) temp.obj 是否有另一种方法将 GNode 对象存储到通用中?谢谢,如果我不清楚,请告诉我重新措辞

GSTACK 代码

import linearnode.*;
import dataobjects.*;
public class GStack <E>
{
    GNode top;
    //-----------constructors ---------
    public GStack()
    {
        top = null; //--empty stack----
    }
    //-----methods -------
    public void push (E newObj)
    {
        GNode temp = new GNode (newObj);
        if(top != null){
            temp= temp.next;
            top = temp;
        }
    }

    public E pop ()
    {
        if(top != null){
            E temp = (E)top;
            top = top.next;
            return temp;
        }
        else return null;
    }

    //--utility methods --
    public boolean isEmpty(){
        if(top == null) 
            return true;
        else
            return false;
    }

    public void traverseGStack(){ //to observe contents of the GStack
        if(top != null){
            GNode temp = top;
            while (temp != null){
                **E obj =  (E)temp.obj;** // this might be wrong
                System.out.println(obj.getData()); //as implemetned BUT in normal stack use : temp.obj.getObj()               
                temp = temp.next;
            }
        }
    }
}

GNode 还需要泛型:GStack<E> 包含一个名为 topGNode<E>,它有一个名为 obj 的字段,类型为 E

E temp = (E)top;

这是错误的。 topGNode,不是 E

**E obj = (E)temp.obj;** // this might be wrong

不,没关系 - 尽管如果您的 GNode class 也被泛型化,您将不再需要强制转换为 E,这很好。