File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toArray function of ArrayList

 
Rekha Gaikwad
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20835
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic