Java for loop in class

I am a beginner programmer, and I am creating this program where I would like to create a list of logical elements of size ten, and then set all values ​​to false. As I understood it in Java, you should not place code directly in a class without surrounding it with a method. However, I want this to be done as soon as an instance of the class is created.

My question is where this should be done. Should I do this in the constructor, should I initialize the list with all its values, or just skip something that makes it completely fine, to put the for loop directly into the class? Thank.

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

boolean[] numKeysPressed = new boolean[10];


for(int i = 0; i<10; i++){
    numKeysPressed[i] = false;
}
+4
source share
5 answers

, , .

, . ..

, , .

, ,

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, boolean[], false, .

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

}
+7

.

public class MyClass{

    boolean[] numKeysPressed = new boolean[10];

    public MyClass(){
        for(int i = 0; i < numKeysPressed.length; i++){
            numKeysPressed[i] = false;
        }
    }

}

, , .

+2

, constructors (< = ) . Java .

, boolean false. for - boolean false .

+1

, Java 0.

, boolean 0- , false.

So, if you have an instance variable (a variable created outside of any methods), it will be by default false.

Having this line somewhere in your class (and outside the method) will do the trick:

boolean [] array = new boolean[7];

And there arraywill be a list of 7 type elements booleanwhose values ​​are all false.

+1
source

You can initialize the array as a private member as follows:

public class myClass {
     private boolean array1[] = new boolean[] {false, true, false};
}

or do it in the constructor as follows:

public class myClass {
   private boolean array2[] = null;
   public myClass () {
     Arrays.fill(array2, false);
  }
}
0
source

Source: https://habr.com/ru/post/1589289/


All Articles