Question

I have read Effective Java which emphases on using Interfaces where possible as return types. Extending the argument I was wondering which of the following methods was preferred / considered a good practice.

OPTION 1:

 Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>(); // Interface 'Set' declared in type
 for (int v = 0; v < graph.getNumberOfVertices(); v++) {
     map.put(v, new HashSet<Integer>());
 }

OPTION 2:

Map<Integer, Set<Integer>> map = new HashMap<Integer, HashSet<Integer>>(); // Class 'HashSet' declared in type.
for (int v = 0; v < graph.getNumberOfVertices(); v++) {
    map.put(v, new HashSet<Integer>());
}
Was it helpful?

Solution

Definitely option 1 should be used. Option 2 won't compile, because a Map<Integer, HashSet<Integer>> is not a Map<Integer, Set<Integer>>.

OTHER TIPS

Yes, generally prefer interfaces for type arguments, unless you have specific reasons to force the users of your interface to use a specific implementation.

In this case, assuming you are going to be returning map, value of map will be cast to Map<Integer, Set<Integer>> map in the assignment.

EDIT: Except that won't work because in java, because Java doesn't support covariant type parameters, so Map<Integer, HashSet<Integer>> isn't a `Map>. But it would work in Scala ;)

Option 1 is the more generic option assuming the errors others have pointed out.

This type of programming is generally the more useful version as it can be used for all types of Sets. This way you don't have to write multiply versions of said code if you were using a different set type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top