File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayList " Watch "ArrayList " New topic


suavedeep kaur
Ranch Hand

Joined: Jun 02, 2008
Posts: 36
i am trying to create an ArrayList and then display it using an Array but theres an exception at runtime

please explain me whats the problem ???
[Dave - formatted and added code tags]
[ July 26, 2008: Message edited by: David O'Meara ]

Suavedeep kaur
Agarwal Priyanka

Joined: Jul 25, 2008
Posts: 20
the better way to examine any exception is using the try-catch block. you must try that to find the exception first.

keep trying...thats the way to success...<br />with best regards...<br />p.agarwal
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Providing the exceprion that gets thrown would also be helpful.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20274

Here's the output:

Now this makes sense. Your ArrayList contains Strings. Then, when using the toArray method, you try to put all those elements into an Integer[]. Of course Integer[] cannot store String, that's where the ArrayStoreException comes from. As specified in the Javadoc of java.util.Collection:

Change Integer[] to String[] and it will work.

Mind you, I do think this is a mistake in the API. The method signature is "<T> T[] toArray(T[] a)" - it should have been "<T super E> T[] toArray(T[] a)" to enforce that T is E or a superclass of E (or an interface that is implemented by E). In your example, with E being String, that would limit T to one of the following:
- String
- Object
- Serializable
- CharSequence
- Comparable<String>
[ July 26, 2008: Message edited by: Rob Prime ]

How To Ask Questions How To Answer Questions
suavedeep kaur
Ranch Hand

Joined: Jun 02, 2008
Posts: 36
thanks alot for the help Rob
I agree. Here's the link:
subject: ArrayList
It's not a secret anymore!