Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this code block?

Tags:

java

I am trying to filter out some of the data from a List of Entity Objects. Here is my sample code:

List<Student> lstUniversalEvents = getAllStudentEvents(StudentID,startTime,endTime);
List<Student> lstTriggerEvents=null;

if(lstUniversalEvents.size()>0)
{
    for (Student event1 : lstUniversalEvents) 
    {
        if(strHighSchool.equals("true"))
        {
            if(event1.getClass().equals("HIGH_SCHOOL"))
            {
                lstTriggerEvents.add(event1);
            }
        }
    }
}

The line lstTriggerEvents.add(event1); is throwing a java.lang.NullPointerException.

Trouble-shooting, I found the following:

  1. The lstUniversalEvents list has data.
  2. condition if(lstUniversalEvents.size()>0) was PASSED
  3. condition if(strHighSchool.equals("true")) was PASSED
  4. condition if(event1.getClass().equals("HIGH_SCHOOL")) was PASSED

So basically, it's failing to add the event to the new list lstTriggerEvents.

How do I fix this?

like image 693
Ram Avatar asked Dec 10 '25 05:12

Ram


1 Answers

You never initialized lstTriggerEvents, it's still null. Change the declaration to

List<Student> lstTriggerEvents=new ArrayList<Student>();

When you declare a variable you have to initialize it, otherwise the JVM assigns a default value. For reference types (like your list) that value is null.

like image 103
Nathan Hughes Avatar answered Dec 11 '25 19:12

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!