How does java generics syntax help avoid type casting?

前端 未结 2 511
天涯浪人
天涯浪人 2021-01-29 08:17

Below is the code,

import java.util.List;
import java.util.ArrayList;


public class Dummy {
    public static void main(String[] args) {
        List

        
2条回答
  •  感情败类
    2021-01-29 08:42

    From farther down in the class:

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
    
    public E get(int index) {
        rangeCheck(index);
    
        return elementData(index);
    }
    

    That @SuppressWarnings tells the compiler that you're sure about the unchecked cast that you're performing there. Since all of the other operations, such as get(int), use the type parameter E, this restricts the unsafe type handling to specific locations where the implementer can make sure to handle the cast correctly.

提交回复
热议问题