0

I have code as:

ArrayList[] arraylist=new ArrayList[2];
    arraylist[0].add("Ngyen");
    arraylist[0].add("Van");
    arraylist[0].add("Jone");

    arraylist[1].add(20);
    arraylist[1].add(40);
    arraylist[1].add(28);
    System.out.println(arraylist[0]);
    System.out.println(arraylist[1]);

i try add value by add method, when at runtime, have a java.lang.NullPointerException, somebody can help me for this.

Quan Nguyen
  • 698
  • 1
  • 9
  • 19
  • The array you have create provides for 2 possible elements of type `ArrayList`, but does not initialise either of those slots, so they are `null`. Respectfully, this is Java 101 basics – MadProgrammer Jul 29 '15 at 04:13
  • You are creating the array of ArrayList in your code and then assigning string values to 0 and 1st index of array without initializing those positions for an arraylist object. Its not right. – Amit Bhati Jul 29 '15 at 04:19

3 Answers3

3
ArrayList[] arraylist=new ArrayList[2];

This create an array named arraylist which can hold 2 ArrayList but not initialized yet means arraylist[0] and arraylist[1] is currently null. So arraylist[0].add("Ngyen"); will give you NullPointerException.

An ArrayList of string can be initialized by the following:

ArrayList<String> list = new ArrayList<String>();

Or you can try this:

arraylist[0]= new ArrayList();
arraylist[1]= new ArrayList();
arraylist[0].add("Ngyen");
...

Run live.

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
1

Your first statement

ArrayList[] arraylist=new ArrayList[2];

allocates an array object that can reference two ArrayList(s). It doesn't instantiate those ArrayList(s). And raw-types are a bad idea. But you could add something like,

ArrayList[] arraylist = new ArrayList[2];
arraylist[0] = new ArrayList();
arraylist[1] = new ArrayList();

And I get

[Ngyen, Van, Jone]
[20, 40, 28]

But the above has no type safety. As you added String and Integer instances to the two List(s).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
-2

try this.

ArrayList[] arraylist=new ArrayList[2]; // creating an array to hold two array list.

// these two statements got missed while copy and paste from my Editor, Apologies for that. 
arraylist[0] = new ArrayList();
arraylist[1] = new ArrayList();

arraylist[0].add("Ngyen");
arraylist[0].add("Van");
arraylist[0].add("Jone");

arraylist[1].add(20);
arraylist[1].add(40);
arraylist[1].add(28);
System.out.println(arraylist[0]);
System.out.println(arraylist[1]);
Prateek Jain
  • 1,504
  • 4
  • 17
  • 27