简体   繁体   中英

How to avoid null pointer error

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;
}

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); 

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?

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.

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.

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;
  }

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

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

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

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[]) ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM