gpt4 book ai didi

java - 如果使用可以返回 null 的函数

转载 作者:行者123 更新时间:2023-11-29 03:48:48 25 4
gpt4 key购买 nike

有一个函数 get() 返回一个值,如果它存在于 ArrayDeque 中,否则返回 null 即 x 可以是某个值或 null。如果 get() 返回 x,那么函数 B() 应该执行一些计算,否则不应该做任何事情。

T get()
{
//compute x
return x;
}

void B()
{
int z;
if(y.get()!=null)
{
z=y.get(); // gives null pointer exception
.....
}
}

问题是 y.get() 已经返回了没有分配给任何变量的值,因此给出了空指针异常。如果我使用类似 if((z=y.get()) != 0) 的东西,它会在 x 为 null 的情况下给出异常。我怎样才能实现这个功能?

最佳答案

我怀疑这是一个 ArrayDeque<Integer> ,对吧?

当你有:

int z = y.get();

这就像在说:

int z = ((Integer) y.get()).intValue();

只需使用:

Integer z = y.get();

相反。然后你可以测试是否z一片空白。另一方面,如果 y.get()已经返回了一个非 null 值,如果它then 返回一个 null 我很惊讶值(value)——你会期望它两次返回同样的东西,对吧?是否涉及其他线程?

另外,不清楚你的意思:

The problem is that y.get() already returns the value which is not assigned to any variable, thus gives null pointer exception.

我看不到这里的“thus”在哪里...调用一个方法并且不将返回值存储在变量中是可以的。如果那是抛出 NullPointerException , 它真的会暗示 y一片空白。当然,如果您发布一个简短但完整的程序来演示问题,那么所有这些问题都会更容易诊断。

顺便说一句,不清楚你为什么调用 y.get()首先是两次。我会将代码重组为:

void B()
{
Integer z = y.get();
if (z != null)
{
// Use z
}
}

真的想调用它两次吗?

关于java - 如果使用可以返回 null 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9679179/

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