CompareTo() Java 快速问题
我的代码中有这个方法
public boolean has(AnyType x){
for(int i=0; i<items.length; i++)
if(items[i] == x)
return true;
return false;
}
,我想重写 if 语句以使用compareTo() 方法,根据我的记忆,它应该是这样的:
if(items[i].compareTo(x) == 0)
但这给了我一个错误
Exception in thread "main" java.lang.NullPointerException
关于我可能是什么的任何想法做错了??
I have this method in my code
public boolean has(AnyType x){
for(int i=0; i<items.length; i++)
if(items[i] == x)
return true;
return false;
}
and I want to rewrite the if statement to use the compareTo() method, and according to what I remember it should be something like this:
if(items[i].compareTo(x) == 0)
But that is giving me an error
Exception in thread "main" java.lang.NullPointerException
Any ideas of what I might be doing wrong??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的一项[] 为空。
检查元素是否正确设置为非空值。
One of your items[] is null.
Check if the elements are properly set to non-null values.
应用程序抛出NullPointer异常在需要对象的情况下尝试使用 null。检查您的
items[i]
值。其中一个值必须为 null,这就是编译器抛出 NullPointerException 的原因。当您执行此操作时,您试图将 null 值与
x
进行比较,这确实会引发NullPointerException
。请检查
not-a-null-value
测试。试试这个,NullPointer Exception is thrown when an application attempts to use null in a case where an object is required. Check with your
items[i]
values. One of the value must be a null, so that's why the compiler is throwing aNullPointerException
.When you do this, you are trying to compare a null value with
x
, which indeed throws aNullPointerException
.Do check for the
not-a-null-value
test. Try this,您的其中一项为空,您可以在尝试调用
compareTo
之前验证它。您还可以使用增强的 for 循环:
One of your items is null, you can validate it before attempting to call
compareTo
.You can also use the enhanced for loop: