Wednesday, 7 August 2013

why can't cast Object[ ] to String[ ]

why can't cast Object[ ] to String[ ]

1.No error
Object[] a = new String[]{"12","34","56"};
String[] b= (String[]) a;
2.No error
Object a = new String[]{"12","34","56"};
String[] b= (String[]) a;
3.Run time error : ClassCastException
Object[] a = new Object[3];
a[0]="12";
a[1]="34";
a[2]="56";
String[] b= (String[]) a;
4. Run time error : ClassCastException
Object[] a = {"12","34","56"};
String[] b = (String[]) a;
Of course, we can downcast an Object[ ] variable back to String[ ] if it
was created as an String[ ].
My question is why we can not cast Object[ ] to String[ ] when it was
created as Object[ ] but all its members are String? Is it because of
security reason or just not that useful to implement this?

No comments:

Post a Comment