aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting Arrays" Watch "Casting Arrays" New topic
Author

Casting Arrays

victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
class Zippy
{
String[] s1 = new String[] { "a", "b"};
Object[] o2 = new String[] {"x","y"} ;
String[] s2 = ( String[] ) o2; //1
s1 = ( String[] ) o2; //2
}

The above code does not compile; the error is at //2. But //1 is fine.

Will somebody explain to me what is going on here, please.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The problem here is not the cast. The problem is that the last line cannot be placed outside of a method or block in the class definition.

If you do this, it will compile okay.

victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
Thanks
raja kanak
Ranch Hand

Joined: Oct 18, 2006
Posts: 135

When i try to compile the above code,
//A shows incompatible types
//1 & //2 shows inconvertible types

I don't know where Im wrong.


live
Anton Uwe
Ranch Hand

Joined: Jan 10, 2007
Posts: 122
Mhhh,
in my opinion this code should compile fine...
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
... and so it does, for me.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
The code does not compile for me. And Keith's explanation is correct.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Originally posted by victor kamat:
The code does not compile for me. And Keith's explanation is correct.


We know that your original code doest not compile.

We are writing about the corrected code with the instance initializer - not your original code. raja kanak claims in his post that it does not compile.
Raji Rama
Greenhorn

Joined: Jan 16, 2007
Posts: 5
hi,
for me too the modified code by keith is showing same error


Zippy.java:4: incompatible types
found : java.lang.String[]
required: Object[]
Object[] o2 = new String[] {"x","y"} ;
^
Zippy.java:5: inconvertible types
found : Object[]
required: java.lang.String[]
String[] s2 = ( String[] ) o2; //1


^
megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
I dont get how here we are able to cast an Object[] to String[]

and in the thread below we said we cant do tht

--------------------------
import java.io.*;
import java.util.*;

public class Box
{
public static void main(String[] args) throws Exception
{
List<String> a = new ArrayList<String>();
a.add("a");
String[] str = (String[])a.toArray();
}
}

The above code compiles, but throws a ClassCastException at runtime. Why ?
If the exception is going to be thrown why does the code compile ?
--------------------------------------------------------------------------------
Posts: 57 | Registered: Jan 2007 | IP: Logged

victor kamat
ranch hand
Member # 141779
posted Friday, February 23, 2007 8:25 AM
--------------------------------------------------------------------------------
The reason I am suprised at the ClassCastException is that aList contains all String objects.

( I do know the correct way to convert aList to a String[] array:
String[] str = aList.toArray(new String[0]); )
--------------------------------------------------------------------------------
Posts: 57 | Registered: Jan 2007 | IP: Logged

Keith Lynn
ranch hand
Member # 92256
posted Friday, February 23, 2007 1:45 PM
--------------------------------------------------------------------------------
The toArray() method without parameters returns a reference to an Object[]. You cannot cast that to a String[].
--------------------
Anton Uwe
Ranch Hand

Joined: Jan 10, 2007
Posts: 122
@Raji Rama
Which java version do you use?


@meg jos
Well, the casting from Object[] to String[] isn't the problem in the other thread. The problem there is that the Object[] really is an array of objects (all elements are of type Object). It is not possible to "convert" this array of Object to an array of String.
Here, in our code in this thread, the Object[] is an array of String. So, all elements are of type String (not of type Object). If you have
ob is an array of Object (though all elements are even of type String).
"String[] str = (String[])ob; " will compile but will throw a ClassCastException.

Edit: Misleading wording corrected and expanded.
[ March 01, 2007: Message edited by: Anton Uwe ]
megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
Thanks for the insight
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi,

I find a lot of confusion among folks regarding the the array casting. My practical finding got out following factors:
First let�s look at the following code snippet:

class Zippy
{
String[] s1 = new String[] { "a", "b"};
Object[] o2 = new String[] {"x","y"} ;
String[] s2 = ( String[] ) o2; //1

{
s1 = ( String[] ) o2; //2
}

}

Line 1 and Line 2 just compiles fine and run code run without any runtime exception. Casting o2 to s2 is must because you can�t convert from Object to String. There is no runtime exception because the runtime type of o2 is String means it refers to an String array.

There will only be run time exception when the run type mismatches. See this:

Object[] o3 = new Object[] {�xx�,�yy�};
System.out.println(o3.getClass());//prints java.lang.Object

System.out.println(o3[0].getClass());//prints java.lang.String

//Don�t get confused with the element types, any element of Object array may be Integer, Float or even Animal and Dog. There is nothing like homogeneous elements in an objects array. There is array of refereneces of Object and Object class is Daddy of all classes so it can have reference of any class Object.

From exam point of you and on the job too remember:
For casting what exactly we require is the matching of run type of the object and not what actually the types of elements.

Ok now see this:

List<String> aList = new ArrayList<String>();
aList.add(�Liz�);
aList.add(�Mack�);
aList.add(�Smack�);

Object[] oarr = aList.toArray();
Always remember toArray() version of this method returns the reference of Object array so you must not mistake by actually seeing the element types the oarr is pointing to.
System.out.println(oarr.getClass());//prints java.lang.Object
System.out.println(oarr[0].getClass());//prints java.lang.String


Again repeating, while casting we require the reference of the object that refers to the array of objects and not what, each element of reference of array is pointing to.

See the list containing heterogenous (different types of )elements.

//Raw type list

List alist = new ArrayList();
alist.add(new Integer(12));
alist.add(new Double(12.33));
alist.add(new String(�cm�));
alist.add(new Animal());

Object[] oarr = alist.toArray();

System.out.println(oarr.getClass());//prints java.lang.Object, as it will always be
System.out.println(oarr[0].getClass());//prints java.lang.Integer
System.out.println(oarr[1].getClass());//prints java.lang.Double
System.out.println(oarr[2].getClass());//prints java.lang.String
System.out.println(oarr[3].getClass());//prints examples.scjp.Animal(ofcourcse on //my PC : ) )


Ofcourse if you want toArray() should return the corresponding array type you have one overloaded version of toArray() which looks like the:

T[] args = toArray(T[] args);
But this is only applicable with parameterized List, Otherwise it requires Object[] as argument and returns so too.
In other words you must have parameterized type of List so that while using this overloaded version of toArray() you could pass any other type exception Object[] and get it back.

I hope this little discussion should help you!
Regards,
cmbhatt


cmbhatt
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Casting Arrays