Class IntCounter
java.lang.Object
java.lang.Number
aQute.libg.ints.IntCounter
- All Implemented Interfaces:
Serializable
This is a very simple fast counter without any synchronization. It is
intended to be used as a counter in recursive calls or when you need to use a
counter shared between code and a lambda. In that case you cannot use an int
because it must be final to be used by the lambda. (Smalltalk supported this
in 1972, but alas.) Last, it also has overflow handling for the common math
operations. When operation would overflow, the old value is maintained and an
overflow flag is set.
void foo() {
IntCounter ic = new IntCounter();
doSomething(ic::in);
System.out.println(ic);
}
None of the methods are atomic. The API of AtomicInteger is used so that it
can be replaced when the AtomicInteger is abused for the purpose of this
class.
If an operation would overflow/underflow, overflow boolean is set. An overflowing value is then not set, the old value remains.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionintadd(int value) intdec()Increment the current value.intdiv(int value) doubleIf the overflow flag is set, a NaN will be returnedfloatIf the overflow flag is set, a NaN will be returnedintget()Get the current valuebooleanintinc()Increment the current value.intintValue()booleanbooleanisZero()longintmul(int value) intreset()Reset the counter to zerointset(int newValue) Set a new value and return the previous value.intsub(int value) toString()Returns the String representation of the current value.Methods inherited from class Number
byteValue, shortValue
-
Constructor Details
-
IntCounter
public IntCounter() -
IntCounter
public IntCounter(int n)
-
-
Method Details
-
inc
public int inc()Increment the current value. The old value is returned and the new value is checked for overflow. overflow will keep the old value- Returns:
- the old value
-
dec
public int dec()Increment the current value. The old value is returned and the new value is checked for underflow.- Returns:
- the old value
-
reset
public int reset()Reset the counter to zero- Returns:
- the previous value
-
get
public int get()Get the current value- Returns:
- the current value
-
set
public int set(int newValue) Set a new value and return the previous value. Overflow is cleared.- Parameters:
newValue- the new value- Returns:
- the previous value
-
add
public int add(int value) -
sub
public int sub(int value) -
mul
public int mul(int value) -
div
public int div(int value) -
intValue
-
longValue
-
floatValue
public float floatValue()If the overflow flag is set, a NaN will be returned- Specified by:
floatValuein classNumber
-
doubleValue
public double doubleValue()If the overflow flag is set, a NaN will be returned- Specified by:
doubleValuein classNumber
-
hasOverflow
public boolean hasOverflow() -
toString
-
isZero
public boolean isZero() -
isNotZero
public boolean isNotZero()
-