How are you storing it? In an int[]
array or a List<Integer>
list I assume? That would be the most logical choice. You can then just get the number by intArray.length
or intList.size()
.
Check the Sun tutorials to learn more about Arrays or Collections.
Those are all declared as public static final int
fields? Why don't you just add the count as another public static final int
field? You already know the count beforehand! Or it must be a 3rd party class which you can't change in any way. It should have been more clarified in the original question.
Anyway, you can also consider to grab reflection. Here's an SSCCE:
package com.stackoverflow.q2203203;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Test {
public static final int i1 = 1;
public static final int i2 = 2;
public static final int i3 = 3;
public static void main(String[] args) throws Exception {
int count = 0;
for (Field field : Test.class.getDeclaredFields()) {
if (field.getType() == int.class) {
int modifiers = field.getModifiers();
if (Modifier.isPublic(modifiers)
&& Modifier.isStatic(modifiers)
&& Modifier.isFinal(modifiers))
{
count++;
}
}
}
System.out.println(count); // 3
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…