Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting  RSS feed

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to convert a object to an array?

I have read that you can convert an array to an object but it doesn't mention the other way round!

If this is possible could someone suggest where I start?
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on the Object...check out the toArray() methods in the Collection interface
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to be picky, casting doesn't convert. It changes how you refer to something, but if it isn't already what you say it is casting won't work.

Say somebody gives me a list and I want to use a method that exists only on LinkedList, so I cast it to LinkedList. If the argument is an ArrayList the cast fails at runtime.

So try a cast like:

If the thing in the collection is not a String array we know the cast will fail at runtime. This code will see if we can put String[] in a collection, meaning Java treats String[] as an Object. And see if you can get it back out and cast it. Give it a try and let us know what you see!
[ May 06, 2005: Message edited by: Stan James ]
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you don't convert an array to an object. In Java, arrays ARE objects. No conversion is required.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read that you can convert an array to an object but it doesn't mention the other way round!

As Stan says, you cannot convert an object, but you can change the way it is viewed.

Say you have declared an array like this:



Any of the following is valid:
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!