How might I count the number of int members define

2019-09-21 19:28发布

问题:

I have a class that stores a large number of int member variables, each defined as follows:

public final static int int1 = int1value;
public final static int int2 = int2value;
...
public final static int int106 = int106value;

There is a second class that needs to do a loop based on the number of ints in the first class. How would I go about adding a function to the first class to count these member variables?

回答1:

It's just 106 "public final static int int1 = int1value" in the first class. No List or Arrays.

How lame!

Unfortunately there is no neat way to sum the values of a large number of statics. You could do it using reflection (see @BalusC's answer), or simply by writing a method evaluates hard-wired expressions like:

public static int calculateSum() {
    return int1 + int2 + 
           // and so on
           + int160;
}

public static int calculateCount() {
    return 160;
}

Your real problem is in your program design. The use of statics is dubious, the use of 160 named variables (instead of an array or list) is bad, and even putting the method(s) in a separate class is dubious.

Fix the design problems and you don't have this one.



回答2:

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
    }

}


回答3:

Based on your edit, it seems like you always have 106 numbers, all of which are initialized... is that correct? If so, you don't need to count, just return 106.

EDIT: @PuppyKevin, based on your comment, what you can do is make another constant variable to keep track of the total number of ints in class one, like

public static final NUMBER_OF_INTS_IN_CLASS_ONE = 106;

and just refer to that in class two, like

for(int i = 0; i < ClassOne.NUMBER_OF_INTS_IN_CLASS_ONE; i++)
    // do stuff here

That way you only have to remember to update one place, and it's in the file you're already editing, which will reduce mistakes.

Also, do you have a specific reason for avoiding arrays or collections? If not, as you might expect from the other answers, I encourage you to use one of those. It's better style for a number of reasons, and would eliminate the problem you're asking about in this post.



回答4:

If the values (integers) are stored in a collection (myCollection):

public int getNumberOfInts() {
  return myCollection.size();
}

If it's an array:

public int getNumberOfInts() {
  return myArray.length;
}

Or.. if it's completely different, you could add a counter to the first class and do it like this:

public class MyIntegerStorage {

  int size = 0;

  // ...

  public void addInteger(int i) {
    size++;
    doWhatEverNeedsToBeDoneToAdd(i);
  }

  public int size() {
    return size;
  }

}


回答5:

It's just 106 "public final static int int1 = int1value" in the first class. No List or Arrays.

Don't bother with a function, just hard code 106 in whatever would uses them. It couldn't make your design any worse.



回答6:

Using a collection or an array is the best approach, but assuming you won't take that advise you can use reflections.

public int getIntCount() {
   int count = 0;
   for(Field f: getClass().getDeclaredFields()) 
       if (f.getType == int.class) 
           count++;
   return count;
}

Or assuming you can count the fields yourself. i.e. you know how many fields you put in your class, just return a constant.

public int getIntCount() {
   return 5; // I know there are five because I counted them.
}


回答7:

So how does your first class store these ints ? In a List ? Why not use the collection to return the number of ints stored.

e.g

public class FirstClass  {
   private List<Integer> integers = new ArrayList<Integer>();
   public int size() {
      return integers.size()
   }
}

Note that from a design POV, I'd rather that the first class loops round the ints it's stored and calls out to a client class for each one (I assume the second class has to do something with each int), but that's being a little pedantic.