Catching ArrayStoreException at Compile-time

后端 未结 4 1639
悲哀的现实
悲哀的现实 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:23

    The method Collection.toArray cannot be changed for compatibility reasons.

    However for your own code you can create a (more) type-safe helper method which protects you from the ArrayStoreException if you use your method consequently:

    public static  T[] toArray(List list, T[] t) {
        return list.toArray(t);
    }
    

    This method will reject String[] s=toArray(new ArrayList(), new String[0]); which matches the example case of your question, but beware of the array subtyping rule: it will not reject

    Object[] s=toArray(new ArrayList(), new String[0]);
    

    because of the pre-Generics “String[] is a subclass of Object[]” rule. This can’t be solved with the existing Java language.

提交回复
热议问题