gpt4 book ai didi

java - Eclipse警告: Cannot be null?

转载 作者:行者123 更新时间:2023-12-01 18:40:37 25 4
gpt4 key购买 nike

我认为以下代码来自 Eclipse 的虚假警告,用于计算给定元素在二叉树中出现的次数:

public int count(E item)
{
int count = 0;
Node crnt = root;
//First seek the item in the tree
while (crnt != null)
{
int compare = crnt.data.compareTo(item);
if (compare > 0)
crnt = crnt.right;
else if (compare < 0)
crnt = crnt.left;
else
{
//Shortcut if not allowing duplicate entries
if (!allowDuplicates)
return 1;
count++;
//Duplicates are always stored to the right
while (crnt != null) // <--Warning appears here
{
crnt = crnt.right;
if (crnt.data.compareTo(item) == 0)
count++;
else
break;
}
}
}
return count;
}

(我可以向您展示 Node 类,但这并不奇怪。只是一个代表数据的 E 和两个代表左右子节点的 Node 指针。)

我是否遗漏了什么或者这是 Eclipse 中的错误?因为看起来这是完全有可能的,事实上,一旦用完右子节点,预计在这种情况下 crnt 可能为空。当然,它在第一次遇到此循环时不会为 null,但通常 IDE 足够聪明,能够意识到变量值在循环内何时发生变化。不过,这一次不是。 Eclipse 建议我在上面放置一个 @SuppressWarnings("null") ,或者我可以进入设置并完全关闭此警告,但我认为没有必要,而且我讨厌压制或忽略可能有用的警告。

最佳答案

crnt仍然与 null 不同因为它在 else 可能更改的 if-elseif-else 语句的子句 crnt 。当它到达第二个 while 时,它的值永远不会改变。声明。

它的表现完全符合预期:告诉您 crnt 的值当该代码命中并且 while 中的附加检查时,永远不会为空。不必要的是。

根据 David Wallace 的建议:内循环不可能是 null因为crnt对象已经在 int compare = crnt.data.compareTo(item); 行之前被访问过,本质上构成了 crnt 的先决条件不得为null .

关于java - Eclipse警告: Cannot be null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20061775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com