I have the following code which i have been refining for a school assignment, but there is a null pointer exception that is driving me crazy.
Here is my code:
public static <AnyType extends Comparable<? super AnyType>>
void difference(List<AnyType> L1, List<AnyType> L2, List<AnyType> Difference){
if(L1 == null){
Difference = null;
}
else if(L2 == null || L1.isEmpty() || L2.isEmpty()){
Difference = L1;
}
else{
Iterator<AnyType> iterator1 =L1.listIterator();
Iterator<AnyType> iterator2 =L2.listIterator();
AnyType a = iterator1.next();
AnyType b = iterator2.next();
while(a!=null || b!=null){
int comp = a.compareTo(b);
if(comp > 0)
b =(iterator2.hasNext()) ? iterator2.next(): null;
else if(comp < 0){
Difference.add(a);
a = (iterator1.hasNext())? iterator1.next(): null;
}
else {
a = (iterator1.hasNext())? iterator1.next() : null;
b = (iterator2.hasNext())? iterator2.next() : null;
}
}
if(b==null){
while(a!=null){
Difference.add(a);
a = iterator1.next();
}
}
}
System.out.println("Difference Set: " + Arrays.toString(Difference.toArray()));
}
On the while loop, when a is null the program keeps going into the while and that is not supposed to happen. Can anyone tell me why is this happening? The data i am using to test is:
List<Integer> list3 = Arrays.asList(1,2);
List<Integer> list4 =Arrays.asList(5,17);
List<Integer> listR = new ArrayList<>();
ListsSets.difference(list3, list4, listR);
after a is null the while is supposed to not be executed again but it somehow happens.