Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<Object> to List<CustomClass> [duplicate]

Tags:

java

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?

like image 554
StuStirling Avatar asked May 26 '15 15:05

StuStirling


4 Answers

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.

like image 105
Tagir Valeev Avatar answered Oct 08 '22 07:10

Tagir Valeev


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;
like image 26
Alexander Pogrebnyak Avatar answered Oct 08 '22 07:10

Alexander Pogrebnyak


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;
}
like image 22
Nayuki Avatar answered Oct 08 '22 09:10

Nayuki


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.

like image 29
Arvind Naik Avatar answered Oct 08 '22 08:10

Arvind Naik