Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics problem when using interfaces

 
Rusty Enisin
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use generics in your interface declaration:


Then use it like this:

[ January 04, 2007: Message edited by: Garrett Rowe ]
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that

<? extends Object>

is equivalent to

<?>
 
Rusty Enisin
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent Garrett! I missed using implements StringBuilder<Integer>.

Thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic