문제

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>());
}
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top