Cast java List class

Question: I have an Android mobile phone application and a quick Java question. I have a class method that returns a List Object. In the list I have “otherclass” items. I would like to cast all the “Object” items in that list to “otherclass” that I’d end up with List ‘otherclass’. I was told it could not be done. Is it true? My code:
public class otherclass {    
    public List<Object> getDataList(){}    // It returns a List<Object>
}

public class TestClass extends otherclass{
    // I can't cast its list here to List<otherclass>. Compile fires an error at:
    List<otherclass> o = (List<otherclass>)getDataList();
}
Answer: No, it can be done if the “otherclass” extends Object. We are speaking about subtyping. It is possible to assign an object of one type to an object of another type if that types are compatible. The solution is here:
List<?> which is equivalent to List<? extends Object> allows the functionality you need:

public class otherclass : extends Object {    
    public List<Object> getDataList(){}    // It returns a List<Object>
}

// In your code you can cast it like this:
    List<? extends Object> o = getDataList();
    if( o != null ){
        List<otherclass> myList =  (List<otherclass>) o;
        // From now on you can use myList as a List<otherclass> reference to the List object o;

    }else{
        // Error handling...
    }
Do not forget that when we cast an object reference we are just casting the type of the reference and not the type of the object. Casting won’t change the actual type of the object. Use instanceof to check the real type at runtime.