This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about casting.

 
James Turner
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have a problem which I am not sure why its happening. I have an ArrayList which i add String arrays to (String[]). Then I call the ArrayList's toArray method to convert the array list to an array of String arrays, i.e. a 2 dimensional array.

A call to: myArrayList.toArray(new String[0]); will return an array of Strings (String[]). If i was to have a list of String[] arrays in the array list already, shouldn't I be able to cast the returned String array to a 2 dimensional array? (String[][]).

When I do that I get a class cast exception. Dosn't it make sence what I am doing? I hope I made myself clear.

Thanx for your help.

James
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi James:
arrays are java.lang.Object, no matter what type they are holding. So, an ArrayList that contains String[] arrays, is an ArrayList contains objects.
If you want to convert the ArrayList to an ordinarry array, you need to type:

Object[] myObjectsArray = myArrayList.toArray(new Object[0]);

then, if you want to get the value of the objects inside myObjectsArray, you type:

String[] myStringArray = (String[])myObjectArray[n];//n is the index number

now you end up with a plain String array- String[].
 
James Turner
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic