Why does Java allow type-unsafe Array assignments?

前端 未结 5 1282
孤独总比滥情好
孤独总比滥情好 2020-12-29 09:19

Generally, Java can be considered as a type-safe language. I know that there are some flaws with generics, but I recently came across a Problem I never had before. To break

5条回答
  •  心在旅途
    2020-12-29 10:01

    "Because it has to".

    To elaborate a bit, consider the following example:

    Object[] objects = null;
    if (something) {
        objects = new Integer[10];
    } else {
        objects = new String[10];
    }
    

    Now, how would the Java compiler know which assignments to allow and which to refuse? It can't. The compile-time type is Object so the compiler will let you put any Object in your array, simply because it doesn't have any knowledge of the runtime type of your array.

提交回复
热议问题