D
dev null
Why can't arrays be cast at runtime? Sure, if I mess up and try to
cast an array of, say, Dates into an array of JLabels, then I should
pay the price and get a ClassCastException; but otherwise I would
expect the language to behave as with usual casts. Example:
import java.util.*;
class TryMe
{
public static void main (String args[])
{
Object o[] = {"one", "two", "three"};
// this works but seems a lot klunkier than needs be
String s[] = (String [])(Arrays.asList (o).toArray (new String [] {}));
System.out.println ("class of s: " + s.getClass ());
System.out.println ("class of s[0]: " + s[0].getClass ());
for (int i = 0; i < s.length; i++)
System.out.println ("s[" + s + "] = " + s);
try // this is how I'd like array casting to work
{
String t[] = (String []) o; // line 18
}
catch (Error e)
{
e.printStackTrace ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}
}
output:
class of s: class [Ljava.lang.String;
class of s[0]: class java.lang.String
s[0] = one
s[1] = two
s[3] = three
java.lang.ClassCastException
at TryMe.main(TryMe.java:18)
Also, why can't I catch the ClassCastException?
TIA,
cast an array of, say, Dates into an array of JLabels, then I should
pay the price and get a ClassCastException; but otherwise I would
expect the language to behave as with usual casts. Example:
import java.util.*;
class TryMe
{
public static void main (String args[])
{
Object o[] = {"one", "two", "three"};
// this works but seems a lot klunkier than needs be
String s[] = (String [])(Arrays.asList (o).toArray (new String [] {}));
System.out.println ("class of s: " + s.getClass ());
System.out.println ("class of s[0]: " + s[0].getClass ());
for (int i = 0; i < s.length; i++)
System.out.println ("s[" + s + "] = " + s);
try // this is how I'd like array casting to work
{
String t[] = (String []) o; // line 18
}
catch (Error e)
{
e.printStackTrace ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}
}
output:
class of s: class [Ljava.lang.String;
class of s[0]: class java.lang.String
s[0] = one
s[1] = two
s[3] = three
java.lang.ClassCastException
at TryMe.main(TryMe.java:18)
Also, why can't I catch the ClassCastException?
TIA,