my dog learned polymorphism
The moose likes Java in General and the fly likes Collection.toArray Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Collection.toArray Problem" Watch "Collection.toArray Problem" New topic
Author

Collection.toArray Problem

Jignesh Patel
Ranch Hand

Joined: Nov 03, 2001
Posts: 625

Here is my declaration:
SelectedAsset selectedAsset[]= null;
Collection selectedAssetsCollection;

in the method I am calling follwing code.

selectedAsset = new SelectedAsset[selectedAssetsCollection.size()];
selectedAsset=(SelectedAsset[])selectedAssetsCollection.toArray();

when I checked selectedAssetsCollection.size() returns me size 1.
But it gives me classcast exception, while it contains object of type SelectedAsset.

I wonder for this awkword behave with toArray method.
Jignesh Patel
Ranch Hand

Joined: Nov 03, 2001
Posts: 625

I found this is the work around with the problem.
selectedAsset=(SelectedAsset[])selectedAssetsCollection.toArray(selectedAsset);

But why simple toArray() method is not working. contradictory of toArray(Object[]);
[ September 08, 2005: Message edited by: Jignesh Patel ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Note that toArray() is declared to return Object[]. Also, the underlying collection has no way of knowing what the concrete types for its contents are. You should look at the overloaded version of toArray() that takes an array parameter. If you have problems, use the search tool to find previous discussions here or in the beginner forum.

Layne


Java API Documentation
The Java Tutorial
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Jignesh Patel:
I found this is the work around with the problem.
selectedAsset=(SelectedAsset[])selectedAssetsCollection.toArray(selectedAsset);

But why simple toArray() method is not working. contradictory of toArray(Object[]);

[ September 08, 2005: Message edited by: Jignesh Patel ]


In your orignal version you weren't using toArray(Object[]) because you weren't sending a parameter to it.

Layne
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Collection.toArray Problem
 
Similar Threads
new window parameters
Overriding methods with exception.
Set concept in Java of Collection
NULL Values
list the files or subdirectories ina directory