Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics 'Incompatible Type' Compile-Time Error

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?

like image 476
objectivesea Avatar asked Sep 28 '10 20:09

objectivesea


People also ask

Do generics prevent compile time errors?

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.

Is incompatible types compilation error?

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.

Are generics compile time or runtime?

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".

Do generics prevent type Cast errors?

Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.


1 Answers

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) {

    ...
}
like image 113
jjnguy Avatar answered Oct 14 '22 19:10

jjnguy