This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Casting of Object[] to Animal[] fails Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting of Object[] to Animal[] fails" Watch "Casting of Object[] to Animal[] fails" New topic
Author

Casting of Object[] to Animal[] fails

Alexander Curvers
Greenhorn

Joined: Apr 03, 2009
Posts: 26
Hi

Casting of Object[] to Animal[] fails while the Object[] array contains only Animal objects
when i use a for loop to add each Animal out of the Object[] array to the Animal[] array it works.. but like stated just trying to cast it in one line of code (Animal[]) fails
why is that?
Kevin Workman
Ranch Hand

Joined: Sep 28, 2010
Posts: 151
Can you post the code you're attempting? It seems to work fine for me.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4396
    
    8

How are you creating the Object[]? Because only putting Animals into an Object[] is not enough to make it an Animal[]. You need to have actually created an Animal[] in the first place.
Alexander Curvers
Greenhorn

Joined: Apr 03, 2009
Posts: 26
thank you both for your replies

Matthew Brown wrote:How are you creating the Object[]? Because only putting Animals into an Object[] is not enough to make it an Animal[]. You need to have actually created an Animal[] in the first place.


with [List].toArray() it makes a Object[] so its clear that is the problem maybe there is a better way to convert the list to an array? so it can be cast or doesnt need to be casted

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4396
    
    8

Ah, thought it might be that! There's a trick. You need the version of toArray that takes an argument.
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

So if you try:
it'll return an Animal[].
Alexander Curvers
Greenhorn

Joined: Apr 03, 2009
Posts: 26
Ah thanks Matthew! thats what i needed
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Slightly better, because it creates only one array (with elements) instead of two (one empty one, one with elements):


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: Casting of Object[] to Animal[] fails