This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic method parameter

 
vu lee
Ranch Hand
Posts: 195
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33694
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
vu lee
Ranch Hand
Posts: 195
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic