Java List T[] toArray(T[] a) implementation

后端 未结 7 988
小蘑菇
小蘑菇 2020-12-08 02:15

I was just looking at the method defined in the List interface: T[] toArray(T[] a) , and I have a question. Why is it generic? Because of that fact, m

7条回答
  •  天命终不由人
    2020-12-08 03:11

    It is type-safe -- it doesn't cause a ClassCastException. That's generally what type-safe means.

    ArrayStoreException is different. If you include ArrayStoreException in "not type-safe", then all arrays in Java are not type-safe.

    The code that you posted also produces ArrayStoreException. Just try:

    TestGenerics list = new TestGenerics();
    list.add(1);
    String[] n = new String[10];
    list.toArray(n); // ArrayStoreException
    
    
    

    In fact, it is simply not possible to allow the user to pass in an array of the type they want to get, and at the same time not have ArrayStoreException. Because any method signature that accepts an array of some type also allows arrays of subtypes.

    So since it is not possible to avoid ArrayStoreException, why not make it as generic as possible? So that the user can use an array of some unrelated type if they somehow know that all the elements will be instances of that type?

    提交回复
    热议问题