Yuming Cao
Yuming Cao

Reputation: 955

Generics method not applicable for the arguments

I have a Node<T> (inner) class in Graph<T> class:

public class Graph<T> {
    private ArrayList<Node<T>> vertices;
    public boolean addVertex(Node<T> n) {
        this.vertices.add(n);
        return true;
    }
    private class Node<T> {...}
}

When I run this:

Graph<Integer> g = new Graph<Integer>();
Node<Integer> n0 = new Node<>(0);
g.addVertex(n0);

The last line give me error:

The method addVertice(Graph<Integer>.Node<Integer>) in the type Graph<Integer> is not applicable for the arguments (Graph<T>.Node<Integer>)

Why? Thanks in advance?

Upvotes: 1

Views: 1479

Answers (2)

Amit Deshpande
Amit Deshpande

Reputation: 19185

Your inner class should not override T Since T is already used in outerclass. Consider what can happen if it was allowed. Your outer class would have referred to Integer and Inner class would have referred to another class that too for the same instance.

 public boolean addEdge(Node node1, Node node2) {
        return false;
    }

    Graph<Integer> g = new Graph<Integer>();
    Graph<Integer>.Node n0 = g.new Node(0);// As T happens to be integer you can use inside node class also.

    public class Node {
        T t;
        Node(T t) {
        }
    }

Or you can use Static Inner class since Static Generics Types are different than instance generic types.

For More Explanation you can Refer to JLS # 4.8. Raw Types

Upvotes: 1

Anshu
Anshu

Reputation: 7853

Following code works fine for me. Running on JRE 1.6

public class Generic<T> {
    private ArrayList<Node<T>> vertices = new ArrayList<Node<T>>();

    public boolean addVertice(Node<T> n) {
        this.vertices.add(n);
        System.out.println("added");
        return true;
    }


    public static class Node<T> {
    }

    public static void main(String[] args) {
        Generic<Integer> g = new Generic<Integer>();
        Node<Integer> n0 = new Node<Integer>();
        g.addVertice(n0);
    }


}

Upvotes: 1

Related Questions