Implementation of a common interface with a raw type

I have a common tree, the general parameter is the data type stored by the nodes:

class TreeNode<D>{  
    public D data;  
    .....
}

Then the visitor interface to be used with the tree:

interface Visitor<D> {
    void visit(TreeNode<D> node);
}

Some visitors may use generics:

class DataListCreator<D> implements Visitor<D> {
    List<D> dataList = new ArrayList<D>();
    public void visit(TreeNode<D> node) {
         dataList.add(node.data);
    }
    public List<D> getDataList() {
        return dataList;
    }

But others do not, they would be better placed in a raw class

class NodeCounter implements Visitor {
    private int nodeCount = 0;
    public void visit(TreeNode node) {
        nodeCount++;
    }
    public int count() {
        return nodeCount;
    }

But I do not know how to implement this last case, the code above does not compile, since I have to implement a common interface is not the source. I tried to implement

Visitor<?> 

with the same result. So my question is: I am forced to use a generic type

NodeCounter<D> 

to implement the Visitor? interface.

Thank.

+3
source share
4 answers

the above code does not compile

, . Java 6. ?

, :

class TreeNode<D>{  
    public D data;  
}

interface Visitor<D> {
    void visit(TreeNode<D> node);
}

class NodeCounter implements Visitor {
    private int nodeCount = 0;
    public void visit(TreeNode node) {
        nodeCount++;
    }
    public int count() {
        return nodeCount;
    }
}
+3

Java- , .

, . , TreeNode, :

interface TreeNodeVisitor<D> {
    void visit(TreeNode<? extends D> node);
}

, (?), a TreeNode, , .

interface TreeNode<D> {
    void accept(TreeNodeVisitor<? super D> visitor);
}
+3

- , .

, , , (, , ) ITreeNode, ITreeNode<D>. , , intercace. IVisitor, NodeCounter Visitor.

:

ITreeNode
ITreeNode<D> implements TreeNode

IVisitor
IVisitor<D> implements IVisitor

NodeCounter implements IVisitor

(Note. I used the C # convention for prefix interfaces with I. NodeCountermeans class, and the rest are interfaces ...)

+1
source

Java Generics are explicitly designed to interact with raw types using a method known as Erasure .

Thus, the situation you are describing about is directly supported and should compile normally:

class TreeNode<D>{
    public D data;  
}

interface Visitor<D> {
    void visit(TreeNode<D> node);
}

class NodeCounter implements Visitor {
    private int nodeCount = 0;
    public void visit(TreeNode node) {
        nodeCount++;
    }
    public int count() {
        return nodeCount;
    }
}
+1
source

Source: https://habr.com/ru/post/1730741/


All Articles