java界面避免强制转换

时间:2017-11-10 22:24:33

标签: java interface casting implements

我有两节课。实现“节点”的接口类“Node”和“Nodegraph”。 “节点”有一个参数方法add,其中我使用Node节点作为参数。在NodeGraph中,我需要转换(NodeGraph)节点才能使用NodeGraph对象。有没有更好的方法来避免施法?

import java.util.Set;

public interface Node {
    public String getId();
    public void add(Node node);
    public boolean remove(Node node);
}


import java.util.Iterator;
import java.util.LinkedList;

public class NodeGraph implements Node {

    private int row;
    private int column;
    private String id;
    private LinkedList<NodeGraph> neighbourds = new LinkedList<NodeGraph>();

    public NodeGraph(int row, int column) {
        this.row = row;
        this.column = column;
        id = "" + row + column;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void add(Node node) {
        neighbourds.add((NodeGraph) node);
    }

    @Override
    public boolean remove(Node node) {
        return neighbourds.remove((NodeGraph) node);
    }

}

3 个答案:

答案 0 :(得分:3)

这是因为你neighbourds列表是不变的,这意味着你只能插入参数化类型,在这种情况下是NodeGraph,将列表定义为Node的协变量让你添加Node的任何子类:

private LinkedList<? extends Node> neighbourds = new LinkedList<>();

答案 1 :(得分:3)

我认为您有正当理由将neighbourds列表绑定到NodeGraph类型。 如果是这样,您可以通过参数化Node接口来避免强制转换:

public interface Node< T extends Node<T> > {
    public String getId();
    public void add(T node);
    public boolean remove(T node);
}

public class NodeGraph implements Node<NodeGraph> {

    private int row;
    private int column;
    private String id;
    private LinkedList<NodeGraph> neighbourds = new LinkedList<NodeGraph>();

    public NodeGraph(int row, int column) {
        this.row = row;
        this.column = column;
        id = "" + row + column;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void add(NodeGraph node) {
        neighbourds.add(node);
    }

    @Override
    public boolean remove(NodeGraph node) {
        return neighbourds.remove(node);
    }
}

答案 2 :(得分:2)

您应该使用界面声明neighbors列表(适用于ListNode):

private List<Node> neighbourds = new LinkedList<>();