Why does arraylist class implement List as well as extend AbstractList?

后端 未结 8 2065
青春惊慌失措
青春惊慌失措 2020-12-05 02:29

The implementation of java.util.ArrayList implements List as well as extends AbstractList. But in java docs you can see that AbstractL

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 03:03

    Arrays.asList returns a List. So casting it to ArrayList is not safe as you do not know what type of List is being returned (depends on the array type it's creating the list from). Your second snippet wants an ArrayList implicitly. Hence it fails while your first snippet compiles fine because it expects a List. You can do-

    ArrayList a = new ArrayList(Arrays.asList(stra));
    

提交回复
热议问题