0

I am getting a null pointer exception despite checking with an if statement first whether the value is null. Here is my code:

Collections.sort(taskList,new Comparator<Task>(){ //here is one NPE
        @Override
        public int compare(Item t1,Item t2){
            if((t1.getAssignedString()!=null)&&(t2.getAssignedString()!=null)){ //here is second NPE
            int x=t1.getAssignedString().compareTo(t2.getAssignedString());

            if(x!=0){return x;}
            else{
                Integer x1=(int)(4*(((Task)t1).getAllottedTime()));
                Integer x2=(int)(4*(((Task)t2).getAllottedTime()));
                return x1.compareTo(x2);
            }
            }
            else{System.out.println("null value");
            return 0;}
        }

    });

Why is this check not working? Is there a way round this?

1
  • You are checking t1.getAssignedString(), but not t1. Commented May 3, 2014 at 11:30

3 Answers 3

1

You are checking t1.getAssignedString() is null , you need to check t1!=null.

For the case of t2 also.

Sign up to request clarification or add additional context in comments.

Comments

0

Im guessing that you need to check if the actual instances are not null, like taskList and the individual Item instances when comparing (t1 and t2).

Comments

0

Before using t1 and t2, you should test whether t1 or t2 must not be null

Collections.sort(taskList,new Comparator<Task>(){ //here is one NPE
            @Override
            public int compare(Item t1,Item t2){
                if(t1==null || t2==null){
                  return 0;
                }
                ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.