简体   繁体   中英

Problem with creating generic Stack class in Java that calls methods from LinkedList class

I am trying to create a generic class with basic stack methods including push, pop, etc. I am trying to use type E, but keep receiving error messages such as "E cannot be converted to int". For these methods, I am calling other methods that I created in another file called LinkedList, which has removeLastNode, etc. What am I doing wrong?


public class Stack<E>
{

      private LinkedList Stack = new LinkedList();

      private int size;
      
      private class Node
      {
      private int data;  
      private Node next; 
       
      public Node(int item)
      {
         data = item;
         next = null;
      }
      }
      
      public Stack()
      {
      size = 0;
      }

      public void push(E data)
      {
         Stack.addLastNode(data);
         size++;
      }
      
      public E pop()
      {
         if (size == 0)
            throw new EmptyStackException();
         else
            Stack.removeLastNode();
         size--;
      }
      
      public E top()
      {
        data = Stack.removeLastNode();
        Stack.addLastNode(data);
        
        if (size == 0)
           throw new EmptyStackException();
        else
           return data;
      }
      
      public int size()
      {
      return size;
      }
      
      public boolean isEmpty()
      {
      if (size == 0)
         return true;
      else
         return false;
      }
   }


Stack.java:38: error: incompatible types: E cannot be converted to int
         Stack.addLastNode(data);
                           ^
  where E is a type-variable:
    E extends Object declared in class Stack
Stack.java:53: error: incompatible types: void cannot be converted to int
        data = Stack.removeLastNode();
                                   ^
Stack.java:59: error: incompatible types: int cannot be converted to E
           return data;
                  ^
  where E is a type-variable:
    E extends Object declared in class Stack
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors

You are attempting to return a Node object as an int , which it isn't.

Instead, return the Node object's data field, eg for pop() , which should return int :

Node node = Stack.removeLastNode();
return node.data;

—-

A few bugs, eg in top() check size first in the method, and in pop() you currently don't even have a return statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM