aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic method parameter" Watch "Generic method parameter" New topic
Author

Generic method parameter

vu lee
Ranch Hand

Joined: Apr 19, 2005
Posts: 189
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;
X(){
//get compiler exception
set = new HashSet<? extends Serializable>();
}
//compiler exception
public void addToSet( <? extends Serializable> value){
set.add(value);
}
}
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30752
    
156

Vu,
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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
vu lee
Ranch Hand

Joined: Apr 19, 2005
Posts: 189
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
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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: http://aspose.com/file-tools
 
subject: Generic method parameter