Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, For Loop in Class

I'm a novice programmer and I am creating this program where I would like to create a list of booleans of size ten and then set all the values to false. As I have understood in Java one is not supposed to place code directly in a class without surrounding them by a method. However I want this to be done as soon as an instance of the class is created.

My question is then where this should be done. Should I do this in a constructor, should I initialize the list with all its values or have I simply missed something making it completely fine to put a for loop directly in the class? Thanks.

Some of my code was requested so this is the problem here:

boolean[] numKeysPressed = new boolean[10];


for(int i = 0; i<10; i++){
    numKeysPressed[i] = false;
}
like image 740
Ivar Eriksson Avatar asked Dec 20 '22 03:12

Ivar Eriksson


1 Answers

However I want this to be done as soon as an instance of the class is created.

My question is then where this should be done. Should I do this in a constructor..

Yes, that is perfect place for it since purpose of constructor is to initialize newly created object with proper state.

In case you have few constructors you can use initialization block which will be added at start of each constructor automatically by compiler

class YourClass{

    List<Boolean> list; 

    YourClass(){
        //constructor 1
    }

    YourClass(String s){
        //constructor 2
    }

    {
        //initialization block, will be executed at start of each
        //constructor (right after its super() call).
        list = new ArrayList<>();
        for (int i=0; i<10; i++)
            list.add(Boolean.FALSE);
    }

}

BTW, if by list you mean boolean[] array then it is by default filled with false values so you don't need to set it. Simple

class YourClass{
    boolean[] list = new boolean[10]; // this array will be filed with false

}
like image 95
Pshemo Avatar answered Jan 06 '23 00:01

Pshemo