mgibson
mgibson

Reputation: 6213

ArrayList.toArray() throws NullPointerException

I have declared two ArrayLists in my main class. One is an ArrayList of Routine objects, the other a String array of Routine names. Everytime a routine is constructed, that Routine name as well as being stored in the routine is stored in the Names arrayList.

    static ArrayList <Routine> routineArrayList = new ArrayList <Routine> ();
    static ArrayList <String> Names = new ArrayList <String> ();                    

I have created a JList and use the String Names arrayList to populate it..

    list = new JList(Names.toArray());

All is well, I can select a name and the corresponding Routine is chosen.

The PROBLEM, is each Routine, has it's own ArrayList of Names.

I want to be able to use the selected Routine and populate a JList with the Names INSIDE that Routine. This is what I was trying..

    currentRoutine = routineArrayList.get(intChoice);
    ...
    list = new JList(currentRoutine.Names.toArray());  ******** PROBLEM LINE

System.out.println(currentRoutine.Names.toArray()) gives exactly the same NullPointerException.

It's been grating on me for a while, any help would be sincerely appreciated likewise if any more information is required I will try my best to provide it.

EDIT

Thanks for your answers, It turns out the primary problem was that the names array inside each Routine object hadn't been initalized correctly. However, the problem is still there.

'System.out.println("Choice: " + currentRoutine.names.get(0)); // Or get(x) 

and

'System.out.println("Choice: " + currentRoutine.names.toString() 

both give exactly what they should. The complete names array or element Note: 'System.out.println("Choice: " + currentRoutine.names.toArray() gives the address details etc.

However, when I try

'list = new JList(currentRoutine.names.toArray());' 

I get the same NullPointerException?

Cheers

Upvotes: 2

Views: 3345

Answers (3)

mgibson
mgibson

Reputation: 6213

Thanks for your help guys,

I got it sorted, it was to do with poorly laid out Frames and JLists really. I ended up declaring a new JList of 'names' (Routine.names) inside the selectionListener for my first JList aswell as a new JFrame.

Cheers,

Matthew

Upvotes: 0

user1743383
user1743383

Reputation:

Suggestion: follow the naming convention of fields so static ArrayList <String> names instead of static ArrayList <String> Names

It seems currentRoutine or currentRoutine.Names is null as ruakh mentioned in his answer.

So do a small check of nullability.

Upvotes: 0

ruakh
ruakh

Reputation: 183544

The method ArrayList<String>.toArray() should never throw a NullPointerException, so the problem here is almost certainly that either currentRoutine or currentRoutine.Names is null. You need to examine the code where you populate routineArrayList, making sure that all of its elements are non-null and have non-null Names fields.

Upvotes: 3

Related Questions