This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes toArray function of ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "toArray function of ArrayList" Watch "toArray function of ArrayList" New topic
Author

toArray function of ArrayList

Rekha Gaikwad
Ranch Hand

Joined: Jul 25, 2005
Posts: 36
I am trying to use toArray function of ArrayList..but get an NullPointerException. My code is as follow:

ArrayList a = new ArrayList();
a.add(obj1);
a.add(obj2);
a.add(obj3);
a.add(obj4);
a.add(obj5);

Object obj[] = new Object[5];
obj = (obj[])a.toArray();

After last line I get NullPointer Exception. Can you explain why?
Wentao Liang
Greenhorn

Joined: Oct 05, 2007
Posts: 13
ArrayList a = new ArrayList();
Object[] obj = new Object[5];
a.add(obj[0]);
a.add(obj[1]);
a.add(obj[2]);
a.add(obj[3]);
a.add(obj[4]);


obj = (Object[])a.toArray();//change
Atention bj[i]
michael warren
Greenhorn

Joined: Mar 04, 2004
Posts: 8
I tried your code and it didn't compile - so can't explain how you get a null pointer exception

Don't think (obj[]) a.toArray() makes sense - what do you expect it to do ?

obj = a.toArray() works fine in code below (have replaced object with Strings just for simplicity in example)


[ October 06, 2007: Message edited by: michael warren ]
Rekha Gaikwad
Ranch Hand

Joined: Jul 25, 2005
Posts: 36
I am trying to get array of objects from ArrayList into Objects array. I have just written a sample code. I am using arrayList because I don't know the size of array when I define array for Object. After collecting all objects into an arraylist I want to pass it to Object's array.
I though using toArray() function will help. If you have any example of how to use toArray function without getting any error,it would be great help.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18509
    
  40

I though using toArray() function will help. If you have any example of how to use toArray function without getting any error,it would be great help.


I think the issue here is that we don't know how you even got your code to compile -- much less get an NPE.

If you show us the code that generates the NPE (as the code you've shown us can't), we can help you figure out what is wrong.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: toArray function of ArrayList
 
Similar Threads
dragdrop-colections
splitting up lists
Doubt in toArray() method
mock test for generics & collections
Generics