I am returning a List
of objects with just the type Object
. However I know that these objects are of class CustomClass
in this case.
When I attempt to cast the original list to the CustomClass
I get an error.
This is how I'm working around it currently and it works but I don't like the fact I have a for loop
just to do this.
List<Object> objects = getObjects();
List<CustomClass> customObjects = new ArrayList<>();
for ( Object object : objects ) {
if ( object instanceof CustomClass )
customObjects.add( (CustomClass) object );
}
Any ideas?
If you know in advance that all of your objects are actually CustomClass
objects, you can perform an unsafe cast:
@SuppressWarnings("unchecked")
List<CustomClass> list = (List<CustomClass>)(List<?>)getObjects();
This is the fastest solution; practically in runtime nothing is performed except the variable assignment. However if you're wrong and your list actually contains other objects, you may have an unexpected ClassCastException
later.
If you are absolutely, positively sure that your list contains only CustomClass
objects, you can do this, and silence a lot of warnings in the process
// Note, absense of generic parameter here, this is a first warning you will see
List genericList = getObjects( );
// Expect another 'unchecked' warning here
List< CustomClass > typedList = (List<CustomClass>) genericList;
If you find yourself doing this kind of filtering/casting often, you can write your own type-safe generic method:
List<Object> objects = getObjects();
List<CustomClass> customObjects = myFilter(objects, CustomClass.class);
static <E> List<E> myFilter(List<?> lst, Class<E> cls) {
List<E> result = new ArrayList<E>();
for (Object obj : lst) {
if (cls.isInstance(obj))
result.add(cls.cast(obj));
}
return result;
}
A couple of tips:
When preparing the List
, ensure you add CustomClass
objects to the list.
customObjects.add( (CustomClass) object );
When returning object from your method getObjects()
, this will return list of CustomClass
and not list of Object
.
List<CustomClass> objects = getObjects();
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With