Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic method parameter

 
vu lee
Ranch Hand
Posts: 206
  • 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: 34084
337
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: 206
  • 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: 24208
35
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