Java – is this abuse casting?
I have some object lists
List<MyObject>
But I know it is a list of objects inherited from MyObject
List<ChildObject>
Trying to project from one to another, give me a warning about "unconvertible types" However, if I first convert to an object and then to a list of the second type, the warning disappears
List<ChildObject> myChildList = (List<ChildObject>) (Object) myObjectList
This seems to work properly Do I have any reason not to do so? Will it throw an error, is there a better way or is it considered a bad practice?
Solution
The generic type parameters in the list can help the compiler type check for you at compile time Cast discards this check and moves the check to run time
Yes, if the list contains objects other than childobject, you can Worst of all, the cast may fail in completely irrelevant places. Your code has no cast at all
For example, if you do
// Do the hack; List<ChildObject> myChildList = (List<ChildObject>) (Object) myObjectList; ... // Iterate over your list for (ChildObject c : myChildList) { ... }
In the above example, if myobjectlist has some classes other than childobject, there will be a class cast exception at run time However, it will happen in the title of the for loop, not in your cast
A better approach is to create a childobjects collection and fill it with the contents of the original array