Forcing Map Implementation in Immutable

I am using Immutables Java Library, how can I implement a specific map implementation without using a specific link?

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

      

If I use the above code, the specific one Map

is LinkedHashMap

.

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

      

If I use the above code the link and implementation will be TreeMap

.

Is there a way to specify Map

as a reference, but force it TreeMap

as a specific type?

+3


source to share


1 answer


Absolutely not - and that should be prohibited (i.e.: no option given to you as a user to change it). This is not the case for your library, but any code in general that returns Map

instead of TreeMap

is fine.

Look at another way, if you return Map

, users are not expecting to be called ceilingEntry

on it (available in TreeMap

, but not in Map

) with a link.

java-8 does the same when through it Collectors.toXXX

. For example, it Collectors.toList

explicitly says:



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

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

+1


source







All Articles