如何避免空指针错误

发布于 2024-08-27 13:30:57 字数 642 浏览 3 评论 0原文

我试图找出 2 个 arrayList 的元素是否匹配。 但这段代码给了我错误 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 因为某些元素为 null。

我该如何解决这个问题?

String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));

String choice []={null,"High","Low","High",null,"Medium"}; 
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));

//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
   if(!(m.get(i).equals(n.get(i)))){   
 result= true;
 break;
   } 
} 
    return  result;
}

I trying to find whether the elements of 2 arrayLists are match or not.
But this code give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException since some of the elements are null.

How can I solved this problem?

String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));

String choice []={null,"High","Low","High",null,"Medium"}; 
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));

//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
   if(!(m.get(i).equals(n.get(i)))){   
 result= true;
 break;
   } 
} 
    return  result;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

清欢 2024-09-03 13:30:57

只需使用 Arrays.equals,如下所示:

    String level []={"High","High","High","High","High","High"};

    String choice []={null,"High","Low","High",null,"Medium"}; 

    return Arrays.equals(level, choice); 

Just use Arrays.equals, like so:

    String level []={"High","High","High","High","High","High"};

    String choice []={null,"High","Low","High",null,"Medium"}; 

    return Arrays.equals(level, choice); 
岁月染过的梦 2024-09-03 13:30:57

问题是您在某些元素上调用 equals 方法,而没有首先检查 null

更改为:

for(int i=0; i<m.size(); i++){
   if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){   
     result = true;
     break;
   } 
} 

或者如果您想允许两个 null 值比较相等:

for(int i=0; i<m.size(); i++){
   if (m.get(i) == null) {
     if (n.get(i) != null) {
       result = true;
     }
   } else if(!(m.get(i).equals(n.get(i)))){   
     result = true;
   } 
   if (result) {
     break;
   }
} 

我不明白的一件事 - 为什么当您发现不匹配时将结果设置为 true?如果两个列表匹配,您不想返回 true 吗?否则返回 false 吗?

The problem is that you are calling the equals method on some elements without first checking for null.

Change to:

for(int i=0; i<m.size(); i++){
   if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){   
     result = true;
     break;
   } 
} 

Or if you want to allow two null values to compare equal:

for(int i=0; i<m.size(); i++){
   if (m.get(i) == null) {
     if (n.get(i) != null) {
       result = true;
     }
   } else if(!(m.get(i).equals(n.get(i)))){   
     result = true;
   } 
   if (result) {
     break;
   }
} 

One thing I don't get - why are you setting result to true when you find a mismatch? Don't you want to return true if both lists match and false otherwise?

羁拥 2024-09-03 13:30:57

此问题的根源可能是您使用 null 作为实际值。

只需查看您的代码,您可以使用 enum 并使用 EMPTY 值代替 null。然后您实际上可以在没有空指针异常的列表中进行比较。

看看这个:
http://java.sun.com/docs/books/ Tutorial/java/javaOO/enum.html

也尽量避免使用数组。只需使用 List,但使用正确的类型。不要使用几乎永远无效的 List

null 应该表示错误或仅进行测试。它永远不应该在有效代码中使用,因为您将在运行时创建空指针异常错误。

The root of this problem could be you are using null as an actual value.

Just looking at your code you could use enum and instead of null use an EMPTY value. Then you can actually compare with in a list without nullpointerexceptions.

Check this out:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html

Also try to avoid using arrays. Just use List but use the proper type. Don't use List<Object> that is almost never valid.

null should indicate an error or testing only. It should never be used in valid code as you will create null pointer exception bugs during runtime.

往事随风而去 2024-09-03 13:30:57

如果您知道第一个列表从不包含空值,则切换调用

if(!(n.get(i).equals(m.get(i)))){ 

同时指定 ArrayList是不好的做法,如果它实际上是 String,请使用 List 对象。

if you know the first list never contains nulls switch the call around

if(!(n.get(i).equals(m.get(i)))){ 

also specifying ArrayList<Object> is bad practice, use List<String> if it is actually String objects.

撩发小公举 2024-09-03 13:30:57

首先检查对象是否是同一个对象(或均为空)。在执行 equals() 测试之前检查是否为 null。

    boolean result = true;
    String level[] = { "High", "High", "High", "High", "High", "High" };
    ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));

    String choice[] = { null, "High", "Low", "High", null, "Medium" };
    ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));

    // Check if the two arrayList are identical
    for (int i = 0; i < m.size(); i++) {
      String mElement = m.get(i);
      String nElement = n.get(i);

      if (mElement == nElement) {
        result = true;
      } else if ((mElement == null) || (nElement == null)) {
        result = false;
        break;
      } else if (!(m.get(i).equals(n.get(i)))) {
        result = false;
        break;
      }
    }

    return result;
  }

Check if the objects are the same object (or both null) first. Check for null before you do the equals() test.

    boolean result = true;
    String level[] = { "High", "High", "High", "High", "High", "High" };
    ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));

    String choice[] = { null, "High", "Low", "High", null, "Medium" };
    ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));

    // Check if the two arrayList are identical
    for (int i = 0; i < m.size(); i++) {
      String mElement = m.get(i);
      String nElement = n.get(i);

      if (mElement == nElement) {
        result = true;
      } else if ((mElement == null) || (nElement == null)) {
        result = false;
        break;
      } else if (!(m.get(i).equals(n.get(i)))) {
        result = false;
        break;
      }
    }

    return result;
  }
仙女山的月亮 2024-09-03 13:30:57

像这样重写您的 if 以检查双无效和单无效:

if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))

Rewrite your if like this in order to check for both double-nullity and single-nullity:

if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))
诗酒趁年少 2024-09-03 13:30:57

不要解决这个特定的问题,而是给自己一个可以反复使用的工具,例如:

public static final boolean areEqual(Object o1, Object o2) {
    return o1 == null ? o2 == null : o1.equals(o2);
}

......在一些方便的实用程序类中,然后在循环中使用它。

但当然,对于这个特定要求,推导具有正确答案(使用java.util.Arrays.equals(Object[],对象[]))。

Rather than solving this specific problem, give yourself a tool you can use over and again, e.g.:

public static final boolean areEqual(Object o1, Object o2) {
    return o1 == null ? o2 == null : o1.equals(o2);
}

...in some handy utility class, then use that in your loop.

But of course, for this specific requirement, derivation has the right answer (use java.util.Arrays.equals(Object[],Object[])).

只为一人 2024-09-03 13:30:57

删除 NULL

您可以从 List 中删除 NULL 值处理之前的对象。

myList.removeAll( Collections.singleton( null ) );

集合类是一堆方便的实用方法。不要与 Collection 混淆(单数),父接口 < code>List 并由 ArrayList

请参阅此帖子,Removing all nulls from a List in Java,了解更多信息讨论。

Remove NULLs

You can remove NULL values from your List objects before processing.

myList.removeAll( Collections.singleton( null ) );

The Collections class is a bunch of convenient utility methods. Not to be confused with Collection (singular), the interface that parents List and is implemented by ArrayList.

See this posting, Removing all nulls from a List in Java, for more discussion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文