很难获得此类型安全警告

时间:2016-03-25 06:14:59

标签: java generics nodes suppress-warnings

所以我正在制作一个Path Finder类,它接收一个.txt,它以X为墙,白色空间为开放区域等等。(想想PacMan)。

在我创建的一个Graph类中,我很难尝试实例化Type但是无论出于什么原因,当我给它一个类型时,仍然会有@SupressionWarning(“未选中”)警告。

这是我的Graph类:

public class Graph {

    public Node<String>[][] graphNodes;

    /**
     * The Graph
     * @param rows - number of rows
     * @param columns - number of columns
     */
    @SuppressWarnings("unchecked") // <-- This is what I want to get rid of
    public Graph(int height, int width)
    {
        graphNodes = new Node[width][height];
    }

}

和Node类:

public class Node<T> {

int coordinateX, coordinateY; // Location of nodes in graph.
String data; // To hold data. 
Node<String> cameFrom; // Use to know where the node came from last
boolean visited = false; // Start boolean visited as false for each Node.

public Node(String value, int row, int column) 
{
    coordinateX = row;  
    coordinateY = column; 
    data = value;
}


/**
 * Get the node above the current node.
 * @return the node above the current node.
 */
public static Node<String> getUp(Node<String> current){
    return PathFinder.maze.graphNodes[current.coordinateX][current.coordinateY-1];
}

/**
 * Get the node below the current node.
 * @return the node below of the current node.
 */
public static Node<String> getDown(Node<String> current){
    return PathFinder.maze.graphNodes[current.coordinateX][current.coordinateY+1];
}

/**
 * Get the node to the left of the current node.
 * @return the node to the left.
 */
public static Node<String> getLeft(Node<String> current){
    return PathFinder.maze.graphNodes[current.coordinateX-1][current.coordinateY];
}

/**
 * Get the node to the right of the current node.
 * @return the node to the right.
 */
public static Node<String> getRight(Node<String> current){
    return PathFinder.maze.graphNodes[current.coordinateX+1][current.coordinateY];
}
}

如果有人可以对我发表一些知识,会发生什么事?

1 个答案:

答案 0 :(得分:2)

Oracle docs说:

  

您无法创建参数化类型的数组。

如果您使用原始类型(例如,Node而不是Node<String>,就像您在帖子中显示的那样),则会获得未经检查的转化警告。

相反,请使用ArrayList

public class Graph {

    public List<List<Node<String>>> graphNodes;

    /**
     * The Graph
     * @param rows - number of rows
     * @param columns - number of columns
     */
    public Graph(int height, int width)
    {
        graphNodes = new ArrayList<>(height);
        for (int i = 0; i < height; ++i) {
            graphNodes.add(new ArrayList<>(width));
        }
    }
}

唯一的替代方法(除了抑制未经检查的警告)是在语言规则中使用漏洞并使用无界通配符类型:

public Node<?>[][] graphNodes;

然后:

graphNodes = new Node<?>[width][height];

然而,这是一种糟糕的方法,因为它完全放弃了类型安全性。

P.S。:您发布的Node类根本不需要是泛型类型。只需删除类定义的<T>参数,基于数组的代码就可以正常工作。