For a CS class I am writing a linked list implementation of a linked list interface created by my professor. The assignment requires us to use generics for the list. What I have created, I think, is pretty standard.
public class MyLinkedList<T> implements ADTListInterface {
...
private class Node<T> {
Node<T> head;
Node<T> prev;
public Node(int max) {
...
}
public void shift() {
...
Node<T> newNode = new Node<T>(this.max);
newNode.prev = head.prev;
...
}
}
...
}
At compile time following error is generated:
MyLinkedList.java:111: incompatible types
found : MyLinkedList<T>.Node<T>
required: MyLinkedList<T>.Node<T>
newNode.prev = head.prev;
This error has me very confused. Can anyone explain to me what the issue is?
Using generics in your Java development can help you detect issues during compile time rather than being confronted by them at run time. This gives you greater control of the code and makes the syntax easy to follow. Generics also improves code readability.
Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type. This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety".
Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.
Here is probably the problem:
private class Node<T> {
The <T>
is causing extra problems. Because Node
is an inner class, it doesn't need to declare its generic type again.
You should declare the Node
class like below:
public class MyLinkedList<T> implements ADTListInterface {
...
private class Node {
Node head;
Node prev;
public Node(int max) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With