MDK
MDK

Reputation: 95

Casting arrayList

I would like to cast an arrayList of objects into an arrayList of a specific object class. Cant you do it like when you cast a normal Object ?

JsonParser jParse = CallApi.getUsers(session);
//This object contains users
ArrayList<Object> unknownObject = jParse.getList();
ArrayList<User> users = (ArrayList<User>)unknownObject;

Upvotes: 1

Views: 15906

Answers (3)

Kohler Fryer
Kohler Fryer

Reputation: 764

Here is a helper method I just created for a similar task.

public static <newType, oldType> ArrayList<newType> castArrayList(ArrayList<oldType> list){
    ArrayList<newType> newlyCastedArrayList = new ArrayList<newType>();
    for(oldType listObject : list){
        newlyCastedArrayList.add((newType)listObject);
    }
    return newlyCastedArrayList;
}

it can be used like this

        ArrayList<DesiredObjectType> myArrayList = Util.castArrayList(
               arrayListOfAnotherType            
          );

Upvotes: 1

bvdb
bvdb

Reputation: 24710

This code will always compile. All generics (i.e. <...>) are removed during compilation anyway.

List<User> users = (List)list;

But it's not without risk. If you are sure that your list only contains User objects, then you are safe. However, if there are other objects in the list, then it will probably lead to ClassCastExceptions in other places in your code. (e.g. if you iterate the list with a for(User user : list) loop.

Your IDE may show warnings if you add a cast like this. You can hide these warnings, using annotations (e.g. putting @SurpressWarnings("unchecked") above your method, or the line just above it).

@SuppressWarnings("unchecked")
List<User> users = (List)list;

Upvotes: 0

sohan nohemy
sohan nohemy

Reputation: 615

You can make a function like this.

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

Then use it like this.

    ArrayList<Object> list = new ArrayList<>();
    List<User> users = cast(list);

Upvotes: 0

Related Questions