0

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.

Carlos Luis
  • 173
  • 10
  • 2
    your using `||` , so only one of them has to be true – Ramanlfc Jun 13 '16 at 03:42
  • because you have entered 'OR' condition instead of && operator inside the expression used as while condition. So it should enter inside the while loop even if a is null but b is not null – Jatin Sehgal Jun 13 '16 at 03:45

1 Answers1

0

Use &&, because using || will make your if condition pass if one of them is true. As the result, your code still executing if a not null but b is null.

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
Rudy
  • 6,358
  • 9
  • 42
  • 79