0

I want to compare each elements of two java lists together, the lists could have null elements, but if I use .equals() method I will get a NullPointerExeption. How can I avoid this? How can I improve the code ?

if (l1!=null && l2!=null && l1.size()==l2.size()) {  
    for (int i = 0; i <l1.size(); i++) {
        if (!l1.get(i).equals(l2.get(i))) {  
            return false;     
        }
    } 
}
return true; 

how can I compare null elements in the lists with equal method?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Yasmin
  • 1
  • 1

2 Answers2

0

If the lists may contain null elements, you will need to handle them properly when comparing the elements.

One way to handle null elements is to use the Objects.equals(Object a, Object b) method from the java.util.Objects class. This method compares two objects for equality and returns true if both objects are null or if the a.equals(b), otherwise false.

if (l1!=null && l2!=null && l1.size()==l2.size()) {  
    for (int i = 0; i <l1.size(); i++) {
        if (!Objects.equals(l1.get(i), l2.get(i))) {  
            return false;     
        }
    } 
}
return true; 
Batel
  • 27
  • 1
  • 7
0
l1.get(i).equals(l2.get(i))

throws a NullPointerException only if:

  • l1 is null; or
  • l1.get(i) is null; or
  • l2 is null.

You are checking if either of l1 and l2 are null, but you're not checking if l1.get(i) is null.

To fix this, use !Objects.equals(l1.get(i), l2.get(i)). However, if you may not use Objects.equals, then you have to use null-checks.

!(l1.get(i) == null && l2.get(i) == null || (l1.get(i) != null && l1.get(i).equals(l2.get(i))))
MC Emperor
  • 22,334
  • 15
  • 80
  • 130