Access to hidden getEntry (Object Key) in HashMap

I have a similar problem with the one discussed here , but with stronger practical use.

For example, I have Map<String, Integer>, and I have some function, which is assigned a key, and if the displayed integer value is negative, it puts NULLon the card:

Map<String, Integer> map = new HashMap<String, Integer>();

public void nullifyIfNegative(String key) {
    Integer value = map.get(key);

    if (value != null && value.intValue() < 0) {
        map.put(key, null);
    }
}

In this case, the search (and therefore the calculation hashCodefor the key) is performed twice: one for the search and one for the replacement. It would be nice to have another method (which is already in HashMap) and allows you to make this more efficient:

public void nullifyIfNegative(String key) {
    Map.Entry<String, Integer> entry = map.getEntry(key);

    if (entry != null && entry.getValue().intValue() < 0) {
        entry.setValue(null);
    }
}

The same goes for cases where you want to manipulate immutable objects, which can be map values:

  • Map<String, String>: I want to add something to the string value.
  • Map<String, int[]>: .

, . , , :

  • . , .
  • org.apache.commons.collections.map.AbstractHashedMap ( protected getEntry()), , , generics.
  • , (AFAIK) ( Apache) ( ) maven.
  • , " " (, [, org.apache.commons.lang.mutable.MutableInt] ). , .
  • java.util.HashMap ( java.util) ( java.lang.ClassLoader Class<?> defineClass(String name, byte[] b, int off, int len), . ), JDK, , , , , java.util.

sun.com bugtracker, , , .

, , , !

+3
3

, , .

HashMap<String, String[]> map = ...;

// append value to the current value of key
String key = "key";
String value = "value";

// I use an array to hold a reference - even uglier than the whole idea itself ;)
String[] ref = new String[1]; // lightweigt object
String[] prev = map.put(key, ref);
ref[0] = (prev != null) ? prev[0] + value : value;

, ( B , ). String, hashCode(), . equals(), . ( ) .

+1

, , getEntry -. , , ( , , O (1) ), , .

? - 10 , , , () (: ).

, , - . , , , , , get ( ) set().

+3

There is no performance gain in this proposal, since the card performance in the average case is O (1). But enabling access to the source record in this case will cause another problem. It will be possible to change the key input (even if this is possible only through reflection) and, therefore, change the order of the internal array.

-2
source

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


All Articles