aspose file tools
The moose likes Java in General and the fly likes Why doesn't these assignments work when casting with Generics? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Why doesn Watch "Why doesn New topic
Author

Why doesn't these assignments work when casting with Generics?

Ronnie Phelps
Ranch Hand

Joined: Mar 12, 2001
Posts: 329
List<Object> objectList = new ArrayList();
List<String> stringList = new ArrayList();


objectList = stringList; // This doesn't work

objectList = (List<Object>)stringList; //this doesn't work either
___________________________________________________________________________
Can anyone explain why these two assignments won't work and what needs to be done in order to perform this assignment?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16680
    
  19

Ronnie Phelps wrote:List<Object> objectList = new ArrayList();
List<String> stringList = new ArrayList();


You actually should *not* be doing this -- assigning a non generics collection to a generics one. This is allowed in Java in order to maintain backward compatibility with Java 1.4 and eariler.

Ronnie Phelps wrote:objectList = stringList; // This doesn't work


It doesn't work because it is not a valid assignment. A list of strings can only hold string objects. If you are allowed to assign it to a reference of a list of objects, then you will be able to add any object type list, that another reference believes it to only hold strings.

Ronnie Phelps wrote:
objectList = (List<Object>)stringList; //this doesn't work either


Same reason as previous. Regardless, if you really want to break generics (by casting), then you can do it by casting it to a List that doesn't use generics first.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ronnie Phelps
Ranch Hand

Joined: Mar 12, 2001
Posts: 329

Thanks for your timely response Henry. I also noticed that the first assignment will work if I change the signature of the objectList to be

List<? extends Object> objectList = new ArrayList();


objectList = stringList; // does work now


I understand that it doesn't make since to use generics since we are extending Object. The types in this posting are String and Object in order to simplify my posting. I'm actually using other types in my code. Thanks again.
 
I agree. Here's the link: http://jrebel.com/download
 
subject: Why doesn't these assignments work when casting with Generics?
 
Similar Threads
Usage of wildcard?
Question on Generics
Generics problem- why not taking Animal, Object and super of Dog
Copy existing Array into new ArrayList
JSP variable into javascript