Search code examples
javagenericscollectionscasting

Dynamic casting of Java collection?


 public static void raw2generic(List<Object> ls, Class class)
    {
        //class.cast(ls);
       //List<class> newLs= (List<class>)ls;
    }

I want to cast the raw List (ls) of type Class (class)... class could be legacy classes like Integer.class, String.class etc. ls is guaranteed will be filled with elements of type class. Is it possible?


Solution

  • The following "works" but please heed the warnings in the comments. It is super dangerous.

       public static <T> List<T> raw2generic( List list, Class<T> c ) {
          return (List<T>)list;
       }
       
    

    Note the class type isn't needed, unless you were told to use it and then you probably are expected to actually check the types in the list.

       public static <T> List<T> raw2generic( List list ) {
          return (List<T>)list;
       }
    

    P.S. List<Object> works exactly the same way. It is super super unsafe though.

       public static <T> List<T> raw2generic( List<Object> list ) {
          return (List<T>)list;
       }