[ad_1]
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:
public interface Stack
void push(Object element);
I have implemented this in a simple generic class:
public class NodeStack<T> implements Stack
private Node<T> top;
private int size;
public void push(T value)
if(this.size == 0)
this.top = new Node<>(value, null);
else
this.top = new Node<>(value, this.top);
this.size++;
When I attempt to compile this I get the compiler error messages:
NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other
public void push(T value) {
^
where T is a type-variable:
T extends Object declared in class NodeStack
2 errors
I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.
[ad_2]
لینک منبع