質問

The one main thing I want to avoid while Java programming is excessive boolean variable declarations like this:

public static boolean mytruebool = true, myfalsebool = false, myothertruebool = true, myotherfalsebool = false;

Is there an efficient way (perhaps w/ array usage) of declaring and assigning variables? Any help is greatly appreciated!

役に立ちましたか?

解決 2

If you are comfortable with bit manipulation, you can store all your booleans as a single integer. In this case, you can store your initial state (and other various states) of all the "variables" as a single integer value.

boolean firstVar = false;
boolean secondVar = true;
boolean thirdVar = true;

...can become...

public class Test {

    public static final int INITIAL_STATE = 6;
    private static int myVar = INITIAL_STATE;



    public static boolean getVar(int index) {
        return (myVar & (1 << index)) != 0;
    }



    public static void setVar(int index, boolean value) {
        if (value) {
            myVar |= (1 << index);
        } else {
            myVar &= ~(1 << index);
        }
    }



    public static void printState() {
        System.out.println("Decimal: " + myVar + "  Binary: " + Integer.toBinaryString(myVar));
    }



    public static void main(String[] args) {
        System.out.println(getVar(0)); // false
        System.out.println(getVar(1)); // true
        System.out.println(getVar(2)); // true
        printState();

        setVar(0, true);
        System.out.println(getVar(0)); // now, true
        printState();
    }
}

Learn more about bit manipulation here: Java "Bit Shifting" Tutorial?

他のヒント

If these are fields (static or otherwise), boolean will have an initial value of false. At that point, you set them according to the needs of your program. So at least, you don't have to worry about half of your boolean fields.

If you're discovering that you have too many boolean fields, then you may want to reconsider the design of your program instead of pre-initializing your values.

This should work ; tested already;

      boolean mytruebool,myothertruebool;
      mytruebool = myothertruebool= true;

      boolean myfalsebool,myotherfalsebool;
      myfalsebool=myotherfalsebool=false;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top