Henok Tesfaye
Henok Tesfaye

Reputation: 9560

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?

Upvotes: 0

Views: 246

Answers (2)

Nikolas
Nikolas

Reputation: 44378

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<>();

Upvotes: 2

Progman
Progman

Reputation: 19546

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");

Upvotes: 2

Related Questions