How to cast List<Object> to List

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

This does not compile, any suggestion appreciated.

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


Compil

相关标签:
16条回答
  • 2020-11-27 12:21

    you can always cast any object to any type by up-casting it to Object first. in your case:

    (List<Customer>)(Object)list; 
    

    you must be sure that at runtime the list contains nothing but Customer objects.

    Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.

    0 讨论(0)
  • 2020-11-27 12:23

    Depending on your other code the best answer may vary. Try:

    List<? extends Object> list = getList();
    return (List<Customer>) list;
    

    or

    List list = getList();
    return (List<Customer>) list;
    

    But have in mind it is not recommended to do such unchecked casts.

    0 讨论(0)
  • 2020-11-27 12:26

    Similar with Bozho above. You can do some workaround here (although i myself don't like it) through this method :

    public <T> List<T> convert(List list, T t){
        return list;
    }
    

    Yes. It will cast your list into your demanded generic type.

    In the given case above, you can do some code like this :

        List<Object> list = getList();
        return convert(list, new Customer());
    
    0 讨论(0)
  • 2020-11-27 12:27

    You should just iterate over the list and cast all Objects one by one

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