Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic method parameter  RSS feed

 
vu lee
Ranch Hand
Posts: 208
  • 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
Sheriff
Posts: 36396
453
Eclipse IDE Java VI Editor
  • 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: 208
  • 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
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!