Operator + = is undefined for argument (s) type int, AtomicLong

I have a map as shown below -

ConcurrentHashMap<Long, AtomicLong> histogram = new ConcurrentHashMap<Long, AtomicLong>();

      

This map contains many key value pairs. Placement AtomicLong

as a value was necessary, so I placed it on this map.

So now if I try to iterate through the ConcurrentHashMap

one I mentioned above, it always gives me an error on this line -

buckets[i] += histogram.get(time);

      

as- The operator += is undefined for the argument type(s) int, AtomicLong

I'm not sure how can I fix this problem? I can't go back and change the data structure to everything Integer

instead of Long

and AtomicLong

.

So I need to figure out how to modify the code below in order for it to work. I thought about throwing the whole. But it didn't work either.

Below is my code

private static void logHistogramInfo() {

    System.out.println("From Main Thread: " + histogram);

    int[] definition = { 0, 20, 40, 60, 80, 100 };
    int[] buckets = new int[definition.length];

    for (Long time : histogram.keySet()) {
        for (int i = definition.length - 1; i >= 0; i--) {
            if (time >= definition[i]) {
                      //error on the below line
                buckets[i] += histogram.get(time);
                break;
            }
        }
    }
    for (int i = 0; i < definition.length; i++) {
        String period = "";
        if (i == definition.length - 1) {
            period = "greater than " + definition[i] + "ms";
        } else {
            period = "between " + (definition[i] + 1) + " and " + definition[i + 1] + "ms";
        }
        System.out.println(buckets[i] + " came back " + period);
    }

}

      

+3


source to share


1 answer


The operator +=

was originally intended for use with primitive data types ( int

, long

...). Since they cannot be put into a map, wrapper classes exist. When you use Integer

or long

with any arithmetic operator, they are automatically "unboxed" into the appropriate primitive type.

However, there is no primitive type that matches any AtomicXYZ

. However, you can use any of the methods the class provides Number

to get its value as a primitive eg. longValue()

or intValue()

. Note that the value of your atomic long can in principle be greater than the largest int

(or Integer

), so you may need to deal with potential overflow in some way.



[edit] Or you can use a method get()

as assylias points out (which I didn’t know about since I hadn’t used atomic types before), which does the same as longValue()

for AtomicLong

(and same as intValue()

for AtomicInteger

), as you can see from it implementation.

+4


source







All Articles