Why does Java allow this?

It is syntactically legal to do this:

String [] s = new String[1];
Object [] o = s;

o[0] = new Integer(42);

but of course it will fail at runtime.

my question is: what is the point of allowing this appointment in the first place?

+3
source share
6 answers

The problem is the assignment Object [] o = s;- I assume that you mean "this".

The technical term is covariance of an array , and without it you could not have code that deals with arrays in general. For example, most non-primitive array methods in java.util.Arrayswould be useless, since you could only use them with actual instances Object[]. Obviously, this was considered more important by Java developers than complete type safety.

, Java-, Java 5: . (. ?), Java .

+8

, :

ArrayList[] lists = new ArrayList[10];
lists[0] = new ArrayList();

List[] genericLists = lists;
lists[0].add("someObject");

String → Object, ArrayList → List . - , Java, . , , :

List[] lists = new List[10];
lists[0] = new ArrayList();
lists[0].add("someObject");

, , , , , , , . Object[], . - String[], Object[], , String[], .

+2

, java.lang.ArrayStoreException: java.lang.Integer

, String [] Object [], .

Integer i = new Integer(10);
Object o = i;
String s = (String) o;

, ClassCastExeption .

+1

( ), o String[] , . , , Integer[] o, .

0

, , ( ) . [ArrayStoreException][1], .

:

String [] s = new String[1];
Object [] o = s;

o = new Integer[1];

o[0] = new Integer(1);

. , IMHO Java.

0

Typically, the compiler cannot determine whether it was oassigned as String[]. Consider this:

String[] s = new String[1];
Object[] o;

if (complexFunction(System.currentTimeMillis())) {
  o = s;
} else {
  o = new Integer[1];
}

o[0] = 42;

The compiler will not know at design time what type it owill accept, so it just allows you to assign.

0
source

All Articles