wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Class and Generics ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Class and Generics ?" Watch "Class and Generics ?" New topic
Author

Class and Generics ?

Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
if I only have a Class, how to use generics ?

Like this....


But this can't pass compiler, how to work out ?

Thanks
Gavin Tranter
Ranch Hand

Joined: Jan 01, 2007
Posts: 333
Hi,
Generics uses Type information not the names of instances.
Type information is the name of a class, suct as String or 2DPoint.

Therefore in your example you should replace myClass with Class, as Class is the type of the objects you plan to store in the list.

hope this helps
Gavin
Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
Gavin Tranter wrote:
Therefore in your example you should replace myClass with Class, as Class is the type of the objects you plan to store in the list.


Are you saying

List<Class> peopleList = (List<Class>)anotherList;

But this can't help me. My goal is to dynamically cast a list to another list based on its Class type.

The perfect solution for me will be something like this



How to work out ?

Thanks.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Generics are a compile-time only construct. At runtime, a List contains only Objects; therefore your request really doesn't make any sense; is it not necessary.


[Jess in Action][AskingGoodQuestions]
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
This isn't exactly what you asked for, but you might like Collections.checkedList(). It's not "casting" , but it creates a list that can only contain the specified type. Unless the list already contained some other type within it, in which case you'll get a ClassCastException if you try to access it.
 
Consider Paul's rocket mass heater.
 
subject: Class and Generics ?