Catching ArrayStoreException at Compile-time

后端 未结 4 1667
悲哀的现实
悲哀的现实 2021-01-20 22:40

Consider the following test of Java\'s ArrayList#toArray method. Note that I borrowed the code from this helpful answer.

public class GenericTest {
         


        
4条回答
  •  春和景丽
    2021-01-20 23:25

    ArrayStoreException exists precisely because Java's type system cannot handle this situation properly (IIRC, by the time Generics came along, it was too late to retrofit arrays in the same manner as the collections framework).

    So you can't prevent this problem in general at compile time.

    You can of course create internal APIs to wrap such operations, to reduce the likelihood of accidentally getting the types wrong.

    See also:

    • Dealing with an ArrayStoreException
    • Why are arrays covariant but generics are invariant?

提交回复
热议问题