Why does Java allow type-unsafe Array assignments?

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

    There's Discussion that I found while I google it

    I Found:

    Firstly, arrays do not break type safety. If they did, then upcasting an array wouldn't fail at runtime. They make it impossible for the compiler to prove the program type-safe, so the checking is deferred until runtime.

    I think confusion occurs here because one the one hand, since a String is-a Object an array of Strings is-obviously-an array of Objects, and on the other it clearly isn't. The answer is in the mutability of an array.

    If the array is immutable, then it safe to treat a String[] as an Object[], because an immutable String[] is always exactly like an immutable Object[].

    On the other hand, if the array is mutable, then it is not usually safe to treat a String[] as an Object[].

    The "wildcards" technique described in the above link is exactly what CommonLisp has been doing for years.

    (deftype StringArray? () (array String)) ; This is the type of arrays of String 
    (deftype ObjectArray? () (array Object)) ; This is the type of arrays of Object 
    (subtypep StringArray? ObjectArray?)      ; Is StringArray? a subtype of ObjectArray?? false, true                               ; No, it isn't. (false: it isn't, true: I'm ure) 
    (deftype AnyArray? () (array *))         ; This is the type of arrays of anything (subtypep StringArray? AnyArray?)         ; Is StringArray? a subtype of AnyArray??   true, true                                ; Yes, it is. (true: it is, true: I'm sure)
    

提交回复
热议问题