Why does Java allow type-unsafe Array assignments?

前端 未结 5 1269
孤独总比滥情好
孤独总比滥情好 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:11

    Firstly, I should point out that this is type-safe.

    Object[] objects = new Integer[10];
    objects[0] = "Hello World";
    

    because an exception will be thrown. (It is not statically type-safe ... but that is a different statement entirely.)

    The reason that Java allows this is historical. Until Java 5, Java did not support any form of generics. Gosling has said that if they had had the time to figure out and incorporate generics into Java 1.0, they would have done so.

    Unfortunately, they didn't. But they still wanted to be able write things like a general purpose sort method with the following signature:

        void sort(Object[] array, Comparator comp) ...
    

    To make this method work for any kind of object array (without generics), it was necessary to make arrays covariant; i.e. to make it legal to pass a String[] or Integer[] as an argument where the formal type is Object[]. If they hadn't done that you would have had to copy the String[] to an Object[], sort it, and then copy it back.

提交回复
热议问题