This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting issue

 
Matt Ghiold
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Guys,
I am building an ArrayList of DataInfo objects.
Then, when I return I want to cast it back to an array of DataInfo objects.
So this sample code (very rough):

Now this compiles fine, but at runtime you
get a class case exception, saying that
returnTest is returning an object. Can someone
please explain to me why this is happening,
because my casting should be correct, but
obviously their is something strange I am missing.
Thanks,
 
Cedric Bompart
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just do that
(DataInfo[]) x.toArray(new DataInfo[x.size()]);
 
Matt Ghiold
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cedric,
Thank's a lot that snippet worked great, but I am curious as to why it worked. Can you explain what is happening, because it seems slightly redundant to me, but at the same time it works your way and it doesn't my why, I am just curious as to the logic behind it.
Thanks again,
 
Cedric Bompart
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look in the JDK API, it's nicely explained
-> java.util.ArrayList , public Object[] toArray(Object[] a)
 
Matt Ghiold
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank's a lot!
-Matt
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic