3

I am using Immutables Java library, how can I enforce a specific map implementation, without having to use a specific reference?

@Immutable
public interface ConfigIF {
  Map<String, String> getOptions();
}

If I use the above code the concrete Map is a LinkedHashMap.

@Immutable
public interface ConfigIF {
  TreeMap<String, String> getOptions();
}

If I use the above code both the reference and the implementations are TreeMap.

Is there a way to specify Map as a reference but enforce TreeMap as concrete type?

Andrea Bergonzo
  • 3,983
  • 4
  • 19
  • 31

1 Answers1

1

Absolutely not - and it should be forbidden (that is : no option given to you as a user to alter that). This is not specific to your library, but any code in general that returns a Map instead of TreeMap let' say.

Look it the other way, if you return a Map users are not expect to call ceilingEntry on it (that is available in TreeMap, but not in Map) via cast of the reference.

java-8 does the same thing when via it's Collectors.toXXX. For example Collectors.toList explicitly says:

There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned.

This means that they are allowed to return whatever they find the most appropriate.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Ok, I understand. I only don't get how they can return something appropriate when the user is the only one that knows what implementation will be beneficial. – Andrea Bergonzo Jul 25 '17 at 10:21
  • 1
    @AndreaBergonzo the choice is almost always a series of compromises between speed, memory, etc. Or even an internal data structure that will perform things faster, like `toArray` in java-8 that uses `SpinedBuffer`... – Eugene Jul 25 '17 at 10:42