File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Generic method parameter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic method parameter" Watch "Generic method parameter" New topic

Generic method parameter

vu lee
Ranch Hand

Joined: Apr 19, 2005
Posts: 195
I have a class X implementing Serializable. This class contains a Set in which I want all items adding to it are serializable. I am getting a couple of compiler errors. Is it doable? Could someone suggest or point me to a document? Thanks

class X implements Serializable{
Set<? extends Serializable> set;
//get compiler exception
set = new HashSet<? extends Serializable>();
//compiler exception
public void addToSet( <? extends Serializable> value){
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33113

Why do you need "Set<? extends Serializable>" rather than "Set<Serializable>" ?

The later can contain any class that implements the Serializable interface. Similarly, the add method could just take a Serializable parameter. It doesn't need the generic parameter.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
vu lee
Ranch Hand

Joined: Apr 19, 2005
Posts: 195
Thanks for your quick reply, Jeanne.
Since I need to iterate through items in the set and invoke toString() on each item.
I cannot do that with just Serializable.
Set<Serializable> set = new HashSet<Serializable>();
Iterator<Serializable> itr = set.iterator();
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Originally posted by vu lee:

I cannot do that with just Serializable.

Can't do what now? You can call the methods of Object on any reference variable, including those of interface type.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Generic method parameter
It's not a secret anymore!