Is there a fully universal version of Map.get (), ie, "V get (K key)"

Since Map.get () is not completely general, we often find cases where the developer passed a different type of object (and therefore errors). The frequency of such cases increased when we started using artifacts / services from other teams. What are the reasons why Map.get (Object key) is not (fully) general , explains why get () is not completely general.

Since we actually have no cases of using two objects belonging to different types, but "semantically" equal, the availability of the Map.get () version will really help us identify such errors at compile time. Are there any APIs that can be used in production?

+6
source share
3 answers

This is not a direct answer to your question, but some IDEs (at least IntelliJ) have a check to flag suspicious use of collections, and this is definitely caught by him:

Map<String, Integer> map = new HashMap<String, Integer>(); map.put("hello", 5); //In IntelliJ, this line gives the warning: //Map<String, Integer> may not contain objects of type StringBuilder System.out.println(map.get(new StringBuilder("hello"))); 

You mentioned that you tried to catch these problems at compile time, so I thought it was worth mentioning. You can link this to a static analysis tool for your build server, for example, to search.

In IntelliJ, checking is called calling the Suspicious Collections method.

Edit (2011/10/18)

In FindBugs, it seems that the GC_UNRELATED_TYPES error should catch this (although I have not tried to verify this):

GC: no relation between generic parameter argument and method

This call to the general collection method contains an argument with an incompatible class from the collection parameter class (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding argument of a general type). Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here. Most likely, the wrong value is passed to the method. (...)

+4
source

Here's a helper method that provides verified access:

 public static <K, V> V safeGet(Map<? super K, ? extends V> map, K key) { return map.get(key); } 

Usage example:

 Map<List<String>, Date> map = new HashMap<List<String>, Date>(); // this compiles: Date date = safeGet(map, Arrays.asList("")); // this doesn't Date date2 = safeGet(map, "foo"); 
+2
source

Source: https://habr.com/ru/post/897324/


All Articles