How to cast List<Object> to List

后端 未结 16 983
时光取名叫无心
时光取名叫无心 2020-11-27 11:43

This does not compile, any suggestion appreciated.

 ...
  List list = getList();
  return (List) list;


Compil

16条回答
  •  广开言路
    2020-11-27 12:20

    You can't because List and List are not in the same inheritance tree.

    You could add a new constructor to your List class that takes a List and then iterate through the list casting each Object to a Customer and adding it to your collection. Be aware that an invalid cast exception can occur if the caller's List contains something that isn't a Customer.

    The point of generic lists is to constrain them to certain types. You're trying to take a list that can have anything in it (Orders, Products, etc.) and squeeze it into a list that can only take Customers.

    提交回复
    热议问题