/** * Convenience version of {@link #getAndAdd(int, int)} (key, -1). * * @param key for the counter. * @return the old value. */ public int getAndDecrement(final int key) { return getAndAdd(key, -1); }
/** * Convenience version of {@link #getAndAdd(int, int)} (key, 1). * * @param key for the counter. * @return the old value. */ public int getAndIncrement(final int key) { return getAndAdd(key, 1); }
/** * Add amount to the current value associated with this key. If no such value exists use {@link #initialValue()} as * current value and associate key with {@link #initialValue()} + amount unless amount is 0, in which case map * remains unchanged. * * @param key new or existing * @param amount to be added * @return the new value associated with the specified key, or * {@link #initialValue()} + amount if there was no mapping for the key. */ public int addAndGet(final int key, final int amount) { return getAndAdd(key, amount) + amount; }
@Test public void shouldReturnOldValueForGetAndAddNot0IfKeyExists() { map.put(1, 1); int amount; do { amount = ThreadLocalRandom.current().nextInt(); } while (amount == 0); final int val = map.getAndAdd(1, amount); assertEquals(1, val); assertEquals(1, map.size()); }
@Test public void shouldReturnInitialValueForGetAndAdd0IfKeyMissing() { final int val = map.getAndAdd(1, 0); assertEquals(INITIAL_VALUE, val); assertTrue(map.isEmpty()); }
@Test public void shouldReturnOldValueForGetAndAdd0IfKeyExists() { map.put(1, 1); final int val = map.getAndAdd(1, 0); assertEquals(1, val); assertEquals(1, map.size()); }
@Test public void shouldContainValueForIncAndDecEntries() { map.incrementAndGet(1); map.getAndIncrement(2); map.getAndAdd(3, 2); map.addAndGet(4, 3); map.decrementAndGet(5); map.getAndDecrement(6); assertTrue(map.containsKey(1)); assertTrue(map.containsKey(2)); assertTrue(map.containsKey(3)); assertTrue(map.containsKey(4)); assertTrue(map.containsKey(5)); assertTrue(map.containsKey(6)); }
/** * Convenience version of {@link #getAndAdd(int, int)} (key, -1). * * @param key for the counter. * @return the old value. */ public int getAndDecrement(final int key) { return getAndAdd(key, -1); }
/** * Convenience version of {@link #getAndAdd(int, int)} (key, 1). * * @param key for the counter. * @return the old value. */ public int getAndIncrement(final int key) { return getAndAdd(key, 1); }
/** * Add amount to the current value associated with this key. If no such value exists use {@link #initialValue()} as * current value and associate key with {@link #initialValue()} + amount unless amount is 0, in which case map * remains unchanged. * * @param key new or existing * @param amount to be added * @return the new value associated with the specified key, or * {@link #initialValue()} + amount if there was no mapping for the key. */ public int addAndGet(final int key, final int amount) { return getAndAdd(key, amount) + amount; }