0

I am trying to return a list of integers having length of the list/array passed.

But it's returning null pointer exception error. Should I use any other data structure for the same List, array etc.

What would be the best to be used.

import java.util.ArrayList;

public class App {

    private static ArrayList<Integer> a;

    public static ArrayList<Integer> map(String[] x) {

        for (int i = 0; i < x.length; i++) {

            a.add(x[i].length());

        }

        return a;
    }

    public static void main(String[] args) {

        String[] string = { "hello", "how", "r", "you" };

        System.out.println(map(string).toString());
    }

}
User
  • 483
  • 4
  • 19
  • What do you think is value of `private static ArrayList a;` (hint: what is default value of fields)? – Pshemo Nov 02 '15 at 16:40
  • but how do I initialize it?, I am very new to Java – User Nov 02 '15 at 16:43
  • Create `new` list and *assign* it to `a`. You can do it in same line in which you declared that field, or in some code block like inside constructor. – Pshemo Nov 02 '15 at 16:44
  • ok it works now after doing `private static ArrayList a = new ArrayList();` Ideally compiler should have caught that as not initialized. Is there any other better way of doing it? I don't know why I used ArrayList. – User Nov 02 '15 at 16:49
  • "*Ideally compiler should have caught that as not initialized*" you don't realize yet that `null` is also proper way to initialize variable so compiler can't complain about it (sometimes we don't need all fields to point to real object so `null` is enough). – Pshemo Nov 02 '15 at 16:53
  • "*Is there any other better way of doing it? I don't know why I used ArrayList*" to help you with this you need to explain what you are really trying to do. Why do you need list here? Are you trying to simply print content of arrays? – Pshemo Nov 02 '15 at 16:58

0 Answers0