0

Well, this is somewhat stupid question but I want to explore something new that's why posting this question. Please! before marking it duplicate or irrelevant post your answer.

Q: How to use Array of ArrayList specially when the ArrayList is in other class and Array of ArrayList in main()?

class ArrayListDemo {

private ArrayList<Type> arrList = new ArrayList<Type>();

public void addItem(Type x) { 
       arrList.add(x);
       System.out.println("Type Added: " + x);
    }
}

Now, main() is like:

public void main(String[] args) {
       ArrayListDemo[] arr = new ArrayListDemo[10];
       Type x = somethingSilly;
       arr[0].addItem(x);      // <-- java.lang.NullPointerException
}

What I'm missing or what's wrong with this? I know, there are better options like available List<> etc but I'm given a task to do it just via Array of ArrayList.

  • The code is confusing. classes have to be written starting with an Upercase: so it is class ArrayListDemo. edit your code and question – AlexWien Nov 18 '15 at 19:22
  • @AlexWien they actually don't have to but I agree that they should be. – Mibac Nov 18 '15 at 19:23
  • @AlexWien they don't have to, however it's preferable because it's improves code readability. – hrust Nov 18 '15 at 19:23
  • 1
    The term "have to" is not releated to the compiler, but to recomended minimum java style. – AlexWien Nov 18 '15 at 19:26
  • 1
    Sir, this is just a sample code. In actual code, everything is perfect regarding "Naming Convention". – I_have_No_Life Nov 18 '15 at 19:29
  • When you create an array `arrayListDemo[] arr = new arrayListDemo[10];` All 10 locations of `arr` are null since you did not initialize it with an object. It is just giving you 10 pointers where you can store references to `arrayListDemo` type object. You need to create an object of `arrayListDemo` like this: `arr[0] = new arrayListDemo()` Then you can call `arr[0].addItem(x);` – Atri Nov 18 '15 at 19:32
  • @ashutosh: This worked... ThumpUp – I_have_No_Life Nov 18 '15 at 19:44

2 Answers2

0

arr[0] is null because you didn't populate the array. Example population code:

for ( ArrayList< Type > list : arr)
        list = new ArrayList< Type >( );
Mibac
  • 8,990
  • 5
  • 33
  • 57
0

Because:

arrayListDemo[] arr = new arrayListDemo[10];

Just creates a 10-element array of arrayListDemos, but doesn't actually allocate anything, so the value for each element is the default of null.

blm
  • 2,379
  • 2
  • 20
  • 24