“Warning: [unchecked] unchecked cast” when casting Object to ArrayList

后端 未结 3 1490
轻奢々
轻奢々 2021-01-18 12:09

Strange situation - below is the code:

ArrayList listArr = new ArrayList<>();
Object[] obj = new Object[]{\"str\", listArr};

String st         


        
相关标签:
3条回答
  • 2021-01-18 12:22

    This is because if you try to cast Integer to String you will get ClassCastException at runtime. But there will be no ClassCastException here:

        ArrayList<Integer[]> listArr = new ArrayList<>();
        ArrayList<String[]> list = (ArrayList<String[]>) obj[1];
    
    0 讨论(0)
  • 2021-01-18 12:31

    The compiler complains

    ArrayList<String[]> list = (ArrayList<String[]>) obj[1]
    

    because a cast is a runtime check. So at runtime your ArrayList<String[]> could be a ArrayList<Whatever[]>, because the type of obj is unknown.

    0 讨论(0)
  • 2021-01-18 12:40

    This is because the compiler can not verify the internal types at the list level, so you need to first verify for list. And the internal types individually.

    Instead of ArrayList<String[]> list = (ArrayList<String[]>) obj[1];

    It should be ArrayList<?> list = (ArrayList<?>) obj[1];

    0 讨论(0)
提交回复
热议问题