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

后端 未结 7 982
小蘑菇
小蘑菇 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:18

    It is declared generically so that you can write code such as

    Integer[] intArray = list.toArray(new Integer[0]);
    

    without casting the array coming back.

    It is declared with the following annotation:

    @SuppressWarnings("unchecked")
    

    In other words, Java is trusting you to pass in an array parameter of the same type, so your error does not occur.

提交回复
热议问题