2

Would it possible to create a class like this...

public class Container implements Serializable {
  private final (Map<Object,Object> & Serializable) map;
  public Container( (Map<Object,Object> & Serializable) map) {
    super();
    this.map = map;
  }
  ....
}

Basically, we don't want to bind the map implementation to any class and make sure the implementation implements both Map and Serializable interface.

Many thanks for any idea and help.

William Wong
  • 319
  • 3
  • 12
  • Note that the fact the `Map` implements `Serializable` doesn't mean that the map is serializable - you need all the keys and values to be serializable too (with a little "s" - simply implementing `Serializable` is not enough to guarantee serializability either). – Andy Turner Mar 17 '16 at 10:54
  • Would it be possible for not introducing a new Type Parameter in the class? I don't want to make the implementation specific type affecting the Container's type... @Cootri – William Wong Mar 18 '16 at 10:25

1 Answers1

2

You can define a generic type parameter having the required type bounds :

class Container<E extends Map<Object,Object> & Serializable> implements Serializable {

    private final E map;

    public Container (E map) 
    {
        super();
        this.map = map;
    }

}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks for the example. However, what if we don't want a default constructor? I tried followings, but seems not working well... ` class Container & Serializable> implements Serializable { private final E map; public Container (E map) { super(); this.map = map; } public Container() { this(new HashMap()); } }` – William Wong Mar 18 '16 at 04:01