user198313
user198313

Reputation: 4328

How to cast List<Object> to List<MyClass>

This does not compile, any suggestion appreciated.

 ...
  List<Object> list = getList();
  return (List<Customer>) list;

Compiler says: cannot cast List<Object> to List<Customer>

Upvotes: 145

Views: 312305

Answers (18)

Tamir Adler
Tamir Adler

Reputation: 421

You can't directly cast List to List because Java generics are invariant. This means that List is not the same as List, even though Customer is a subtype of Object.

To handle this, you can stream over the list and cast each element individually:

List<Object> list = getList();
return list.stream().map(Customer.class::cast).toList();

This works because you're casting each individual element, ensuring type safety at runtime. However, be mindful that if any element in list is not a Customer, it will throw a ClassCastException.

Upvotes: 0

Kishan Solanki
Kishan Solanki

Reputation: 14618

SIMPLEST SOLUTION IS TO USE

(((List<Object>)(List<?>) yourCustomClassList))

Upvotes: 1

List<Object[]> testNovedads = crudService.createNativeQuery(
            "SELECT ID_NOVEDAD_PK, OBSERVACIONES, ID_SOLICITUD_PAGO_FK FROM DBSEGUIMIENTO.SC_NOVEDADES WHERE ID_NOVEDAD_PK < 2000");

Convertir<TestNovedad> convertir = new Convertir<TestNovedad>();
Collection<TestNovedad> novedads = convertir.toList(testNovedads, TestNovedad.class);
for (TestNovedad testNovedad : novedads) {
    System.out.println(testNovedad.toString());
}

public Collection<T> toList(List<Object[]> objects, Class<T> type) {
    Gson gson = new Gson();
    JSONObject jsonObject = new JSONObject();
    Collection<T> collection = new ArrayList<>();
    Field[] fields = TestNovedad.class.getDeclaredFields();
    for (Object[] object : objects) {
        int pos = 0;
        for (Field field : fields) {
            jsonObject.put(field.getName(), object[pos++]);
        }
        collection.add(gson.fromJson(jsonObject.toString(), type));
    }
    return collection;
}

Upvotes: -2

roundar
roundar

Reputation: 1713

With Java 8 Streams:

Sometimes brute force casting is fine:

List<MyClass> mythings = (List<MyClass>) (Object) objects

But here's a more versatile solution:

List<Object> objects = Arrays.asList("String1", "String2");

List<String> strings = objects.stream()
                       .map(element->(String) element)
                       .collect(Collectors.toList());

There's a ton of benefits, but one is that you can cast your list more elegantly if you can't be sure what it contains:

objects.stream()
    .filter(element->element instanceof String)
    .map(element->(String)element)
    .collect(Collectors.toList());

Upvotes: 46

Malkeith Singh
Malkeith Singh

Reputation: 245

You can do something like this

List<Customer> cusList = new ArrayList<Customer>();

for(Object o: list){        
    cusList.add((Customer)o);        
}

return cusList; 

Or the Java 8 way

list.stream().forEach(x->cusList.add((Customer)x))

return cuslist;

Upvotes: 4

ayushgp
ayushgp

Reputation: 5091

You can create a new List and add the elements to it:

For example:

List<A> a = getListOfA();
List<Object> newList = new ArrayList<>();
newList.addAll(a);

Upvotes: 2

d0x
d0x

Reputation: 11573

Another approach would be using a java 8 stream.

    List<Customer> customer = myObjects.stream()
                                  .filter(Customer.class::isInstance)
                                  .map(Customer.class::cast)
                                  .collect(toList());

Upvotes: 18

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

Depending on what you want to do with the list, you may not even need to cast it to a List<Customer>. If you only want to add Customer objects to the list, you could declare it as follows:

...
List<Object> list = getList();
return (List<? super Customer>) list;

This is legal (well, not just legal, but correct - the list is of "some supertype to Customer"), and if you're going to be passing it into a method that will merely be adding objects to the list then the above generic bounds are sufficient for this.

On the other hand, if you want to retrieve objects from the list and have them strongly typed as Customers - then you're out of luck, and rightly so. Because the list is a List<Object> there's no guarantee that the contents are customers, so you'll have to provide your own casting on retrieval. (Or be really, absolutely, doubly sure that the list will only contain Customers and use a double-cast from one of the other answers, but do realise that you're completely circumventing the compile-time type-safety you get from generics in this case).

Broadly speaking it's always good to consider the broadest possible generic bounds that would be acceptable when writing a method, doubly so if it's going to be used as a library method. If you're only going to read from a list, use List<? extends T> instead of List<T>, for example - this gives your callers much more scope in the arguments they can pass in and means they are less likely to run into avoidable issues similar to the one you're having here.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can use a double cast.

return (List<Customer>) (List) getList();

Upvotes: 30

Hendra Jaya
Hendra Jaya

Reputation: 71

Similar with Bozho above. You can do some workaround here (although i myself don't like it) through this method :

public <T> List<T> convert(List list, T t){
    return list;
}

Yes. It will cast your list into your demanded generic type.

In the given case above, you can do some code like this :

    List<Object> list = getList();
    return convert(list, new Customer());

Upvotes: 1

nd.
nd.

Reputation: 8932

As others have pointed out, you cannot savely cast them, since a List<Object> isn't a List<Customer>. What you could do, is to define a view on the list that does in-place type checking. Using Google Collections that would be:

return Lists.transform(list, new Function<Object, Customer>() {
  public Customer apply(Object from) {
    if (from instanceof Customer) {
      return (Customer)from;
    }
    return null; // or throw an exception, or do something else that makes sense.
  }
});

Upvotes: 2

irreputable
irreputable

Reputation: 45433

you can always cast any object to any type by up-casting it to Object first. in your case:

(List<Customer>)(Object)list; 

you must be sure that at runtime the list contains nothing but Customer objects.

Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.

Upvotes: 192

Bozho
Bozho

Reputation: 597046

Depending on your other code the best answer may vary. Try:

List<? extends Object> list = getList();
return (List<Customer>) list;

or

List list = getList();
return (List<Customer>) list;

But have in mind it is not recommended to do such unchecked casts.

Upvotes: 41

Rob Sobers
Rob Sobers

Reputation: 21125

You can't because List<Object> and List<Customer> are not in the same inheritance tree.

You could add a new constructor to your List<Customer> class that takes a List<Object> and then iterate through the list casting each Object to a Customer and adding it to your collection. Be aware that an invalid cast exception can occur if the caller's List<Object> contains something that isn't a Customer.

The point of generic lists is to constrain them to certain types. You're trying to take a list that can have anything in it (Orders, Products, etc.) and squeeze it into a list that can only take Customers.

Upvotes: 2

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391316

Note that I am no java programmer, but in .NET and C#, this feature is called contravariance or covariance. I haven't delved into those things yet, since they are new in .NET 4.0, which I'm not using since it's only beta, so I don't know which of the two terms describe your problem, but let me describe the technical issue with this.

Let's assume you were allowed to cast. Note, I say cast, since that's what you said, but there are two operations that could be possible, casting and converting.

Converting would mean that you get a new list object, but you say casting, which means you want to temporarily treat one object as another type.

Here's the problem with that.

What would happen if the following was allowed (note, I'm assuming that before the cast, the list of objects actually only contain Customer objects, otherwise the cast wouldn't work even in this hypothetical version of java):

List<Object> list = getList();
List<Customer> customers = (List<Customer>)list;
list.Insert(0, new someOtherObjectNotACustomer());
Customer c = customers[0];

In this case, this would attempt to treat an object, that isn't a customer, as a customer, and you would get a runtime error at one point, either form inside the list, or from the assignment.

Generics, however, is supposed to give you type-safe data types, like collections, and since they like to throw the word 'guaranteed' around, this sort of cast, with the problems that follow, is not allowed.

In .NET 4.0 (I know, your question was about java), this will be allowed in some very specific cases, where the compiler can guarantee that the operations you do are safe, but in the general sense, this type of cast will not be allowed. The same holds for java, although I'm unsure about any plans to introduce co- and contravariance to the java language.

Hopefully, someone with better java knowledge than me can tell you the specifics for the java future or implementation.

Upvotes: 8

Aric TenEyck
Aric TenEyck

Reputation: 8032

Your best bet is to create a new List<Customer>, iterate through the List<Object>, add each item to the new list, and return that.

Upvotes: 1

vrm
vrm

Reputation: 1422

You should just iterate over the list and cast all Objects one by one

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272247

That's because although a Customer is an Object, a List of Customers is not a List of Objects. If it was, then you could put any object in a list of Customers.

Upvotes: 38

Related Questions