【问题标题】:'x' should probably not be assigned to 'y' warning in intellij'x' 可能不应该分配给 intellij 中的 'y' 警告
【发布时间】:2022-01-29 13:47:31
【问题描述】:

我正在练习二叉搜索树。当我编写这段代码时,intellij 会抛出警告:'x' should probably not be assigned to 'y'。为什么会发生这种情况,我该如何解决?

我假设首先将 null 分配给 y 可能必须对警告做一些事情。但我不确定。

@Setter
@Getter
public class BinarySearchTree {

    private Node root;

    public Node treeInsert(Node z) {
        Node x = root;
        Node y = null;
    
        while (x != null) {
            y = x;  // warning shows in this line
            if (z.key > x.key) x = x.right;
            else x = x.left;
        }
        z.parent = y;
        if (y != null) {
            if (z.key > y.key) y.right = z;
            else y.left = z;
        }
        return z;
    }
    
    @Setter
    @Getter
    private class Node {
        private int key;
        private Node left;
        private Node right;
        private Node parent;
    
        public Node(int key) {
            this.key = key;
        }
    }
}

【问题讨论】:

    标签: java intellij-idea


    【解决方案1】:

    如果看检查说明:

    报告目标变量或函数参数的名称与分配给它的值的名称不匹配的赋值和函数调用。

    示例 1:

    int x = 0;
    int y = x; // x is used as a y-coordinate 
    

    示例 2:

    int x = 0, y = 0;
    // x is used as a y-coordinate and y as an x-coordinate
    Rectangle rc = new Rectangle(y, x, 20, 20);
    

    此检查似乎将您的变量误认为是 xy 坐标,并警告您错误地将 x 坐标值分配给 y 坐标。

    要解决此问题,您应该为变量提供更好的名称:

    public Node treeInsert(Node z) {
        Node currentNode = root;
        Node parentNode = null;
    
        while (currentNode != null) {
            parentNode = currentNode;  // warning shows in this line
            if (z.key > currentNode.key) currentNode = currentNode.right;
            else currentNode = currentNode.left;
        }
        z.parent = parentNode;
        if (parentNode != null) {
            if (z.key > parentNode.key) parentNode.right = z;
            else parentNode.left = z;
        }
        return z;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 2020-04-25
      相关资源
      最近更新 更多