Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

This question already has an answer here:

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.

share|improve this question

marked as duplicate by Sotirios Delimanolis java Nov 18 '15 at 19:23

This question was marked as an exact duplicate of an existing question.

    
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. – Gemma 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
up vote 0 down vote accepted

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

for ( ArrayList< Type > list : arr)
        list = new ArrayList< Type >( );
share|improve this answer
    
I didn't get it. Where this should be done? In main() or in class? – I_have_No_Life Nov 18 '15 at 19:27
    
@I_have_No_Life after you initialize (create) arr variable but before you interact with it (arr.something()). – mibac Nov 18 '15 at 19:28

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.