0

I have a function which is supposed to work with given ArrayList<String> and return the output as ArrayList<Integer>. The problem is NullPointerException is raised on hourList.add(hourInt); and I don't know why.

public ArrayList<Integer> takeTime(ArrayList<String> logs)  {

    ArrayList<Integer> hourList=null;
    Integer hourInt;

    for(String line: logs) {

        String[] matrix = line.split(" ");     
        String[] hour = matrix[3].split(":");
        //  System.out.print(hour[0]+"\n");

       String s = hour[0].replaceFirst("^0+(?!$)", "");

        hourInt = Integer.parseInt(s);
       System.out.print(hourInt+",");

        hourList.add(hourInt);   // <--- NullPointerException here
    }
  return hourList;  
}

System.out.print(hourInt+",");:

  0,0,0,0,1,1,2,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10
XorOrNor
  • 8,868
  • 12
  • 48
  • 81
  • 3
    A generic answer on NPE might be a good reference point but this question was specific to `ArrayList` and it's initialization. – anubhava May 14 '21 at 18:58

3 Answers3

8

You need to construct your ArrayList while declaring it:

ArrayList<Integer> hourList = new ArrayList<>();

Otherwise hourList.add will give NPE since reference hourList is null.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You have to initialize the ArrayList:

List<Integer> hourList = new ArrayList<Integer>;
Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
1

You are trying to call a function of a null object. Try:

ArrayList<Integer> hourList=new ArrayList<Integer>();
Adam Voga
  • 124
  • 9