wood burning stoves 2.0*
The moose likes Java in General and the fly likes Generics problem when using interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics problem when using interfaces" Watch "Generics problem when using interfaces" New topic
Author

Generics problem when using interfaces

Rusty Enisin
Ranch Hand

Joined: May 26, 2005
Posts: 107
Is there a way do implement the following using generics so that you do not have to cast items?



buildString() can accept anything; beans, collections, whatever. Each implementation is for a new type of string builder.

So I would like for each subclass to specify which type of object it can build a string from. For example:



If I don't use the interface there is no problem. It works. But then if I do I might as well just do buildString(Collection items). Any ideas? Or am I just trying to do this all wrong?


The squeaky wheel gets the grease. Well, that or replaced...
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
You can use generics in your interface declaration:


Then use it like this:

[ January 04, 2007: Message edited by: Garrett Rowe ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
As a further thought, the compililer will still issue a warning any time you try to retrieve items from (or add items to ) the raw Collection. If you are just going to build the String by calling toString() on all the elements of the Collection, you can assume its a Collection of Objects:



Caveat: I believe this is correct, but I don't have a compiler handy. YMMV.
[ January 04, 2007: Message edited by: Garrett Rowe ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Note that

<? extends Object>

is equivalent to

<?>


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Rusty Enisin
Ranch Hand

Joined: May 26, 2005
Posts: 107
Excellent Garrett! I missed using implements StringBuilder<Integer>.

Thank you
 
 
subject: Generics problem when using interfaces