Type safety: Unchecked cast from Object to List<MyObject> Type safety: Unchecked cast from Object to List<MyObject> android android

Type safety: Unchecked cast from Object to List<MyObject>


If all you have to work from is an Object, then you can't check at runtime that you actually have a List<MyObject>, because the generic type MyObject is only used for compile-time type checking, it is not available at runtime. This is why you get an error when you try to add the instanceof check.

If you are sure that your Object really is always a List<MyObject> then I'd say the @SuppressWarnings is OK, if you document why you are sure it is not a problem.

If you absolutely want to avoid a warning though, you could create your own List implementation (say, MyObjectList) that is not itself generic but implements List<MyObject>. Then you can do an instanceof check against MyObjectList at runtime.

Another option is to check for and cast to List<?> as the instanceof error suggests. Then you can iterate over the elements in the list and check if they are actually all instances of MyObject, and copy them to a new List<MyObject>.


Well, I finally managed to find a solution.

Just as @Medo42 said:

Another option is to check for and cast to List as the instanceof error suggests. Then you can iterate over the elements in the list and check if they are actually all instances of MyObject, and copy them to a new List.

Even though I did not went through the process of creating a whole new object in order to make this particular case to work "warning-less" this was the right direction to go.

So I took @lokoko 's idea and use it in a new setItems() method, with an Object parameter instead of a List<MyObject> in order to make sure

The result code is the following:

public void setItems(List<MyObject> var){    this.list = var;}public void setItems(Object var){    List<MyObject> result = new ArrayList<MyObject>();    if (var instanceof List){        for(int i = 0; i < ((List<?>)var).size(); i++){            Object item = ((List<?>) var).get(i);            if(item instanceof MyObject){                result.add((MyObject) item);            }        }    }    setItems(result);}

Thanks everyone for your help!


Try something like this :

List<?> result = (List<?>) results.values;for (Object object : result) {    if (object instanceof MyObject) {        tempList.add((MyObject) object); // <-- add to temp    }}filteredItems = tempList; // <-- set filtered