Re: Using generic types in Stack
freddy_engels wrote:
I want to write a method that reverses the order of elements in a
Stack of the generic type E.
For example:
public class MyStack<E> implements MyStackInterface<E>{
private Stack<E> myStack = new Stack<E>();
public MyStack<E> reverse(){
Stack<E> result = new myStack<E>();
You misspelled 'MyStack' here, and you show no indication that 'MyStack' is a
subtype of 'Stack', so this line is doubly doomed not to compile.
while(!myStack.empty()) {
result.push(myStack.pop());
}
return result;
}
}
-------------------------------------------------------------
I keep getting errors with incompatible types. I want this method to
You should have shown us the actual text of the errors, that is, copied and
pasted from your error screen into your post. As markspace said about the
code, so, too, with the error messages.
No doubt your error messages actually told you what the incompatible types
are, a detail you omitted from your post. (Hint, they're 'Stack' and
'MyStack'.) You cannot assign a value of one type to a variable of an
unrelated type.
return a new Stack containing the elements of the old Stack in reverse
order, without changing the state of the original Stack.
'pop()' changes the state of the original Stack.
<http://java.sun.com/javase/6/docs/api/java/util/Stack.html#pop()>
Always read the Javadocs for API methods/classes that you use.
John B. Matthews's suggestion to use 'Deque' should solve your problem. Read
its Javadocs.
Among other things, they tell you: "Deques can also be used as LIFO
(Last-In-First-Out) stacks. This interface should be used in preference to the
legacy Stack class."
How do I correctly instantiate a new instance of a Stack of generic types?
new Stack <E> ()
How do I make a method return a Stack of generic types?
public Stack <E> doSomething() { ... }
I suggest that you read and study the following articles:
<http://java.sun.com/docs/books/tutorial/extra/generics/index.html>
<http://java.sun.com/docs/books/effective/generics.pdf>
--
Lew