简体   繁体   中英

How to cast an Object type into a List<Object> type?

List<Object> frames = new ArrayList();
List<String> names = new ArrayList();

frames.add(names);

//compiler error
frames.get(0).add("ABCD");

Since .get() returns an object type and an Object type doesn't have .add() method the compiler raises an error. How can I cast an object type into a List type?

You can change the generics of the frames variable from Object to List<String> . This way the compiler can see the types which are in the lists, which allows you to use the get(...) method.

List<List<String>> frames = new ArrayList<List<String>>();
List<String> names = new ArrayList<String>();

frames.add(names);

frames.get(0).add("ABCD");

You have 2 choices:

  • Change the frames to List<List<String>> in case the List frames will always contain a List of Strings. It's safe but restricted to a type.

     List<List<String>> frames = new ArrayList<List<String>>(); 
  • Use the type casting while getting. This one is not safe and I recommend you to avoid casting whenever possible. Here it would take place checking if the obtained item from the frames List is really a List itself:

     Object first = frames.get(0); if (first instanceof List) { ((List<String>) first).add("ABCD"); } 

Moreover, try to avoid raw-types. In this case use the diamond <> operators at the declaraion:

List<Object> frames = new ArrayList<>();
List<String> names = new ArrayList<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM