0

How do you manually assign a boolean value to every array positions in just one code line?

Look the code fragment below. I don't wanna manually put a[0]=true; a[1]=true; a[2]=false; ...

public class stackArray {

   static boolean [] a = new boolean [6];

   public static void main(String[] args) {

      a[0]=true;
      a[1]=true;
      a[2]=false;

      for(int i=0; i<6; i++){
         System.out.println(a[i]);
      }

   }
}

I'm really looking something similar to

a= {true, true, false, false, false, false};

but unfortunately it doesn't works :(

Can anybody help me? I googled it but I couldn't find this particular case. Thank you in advance!

azro
  • 35,213
  • 7
  • 25
  • 55
  • 2
    `static boolean [] a = new boolean [6]{true, true, false, false, false, false};` should work. Check top answer to [this question](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java). – AntonH Sep 11 '17 at 15:29
  • @AntonH That will not compile. You probably meant `static boolean[] a = { true, true, false, false, false, false };`. – VGR Sep 11 '17 at 16:27
  • @VGR You're right that it won't compile, but just removing the `6` is enough to make it compile. I didn't test before posting, which is my mistake. Maybe not necessary, but close to OP's original code. – AntonH Sep 11 '17 at 16:36

3 Answers3

0

use the fill method in the Arrays helper class

boolean[] a = new boolean[6];
Arrays.fill(a, true);
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
0

If the array reference is not shared in some other variable then you can just reassign to a new array:

a = new boolean[] {true, .. };

Otherwise if you really want it in one line while keeping the array the same you can do

System.arrayCopy(new boolean[] { true, ... }, 0, a, 0, a.length };

but it doesn't look like better.

Jack
  • 125,196
  • 27
  • 216
  • 324
0

You can do it like this:

boolean [] a = new boolean []{false, false, true};
Julio Daniel Reyes
  • 3,281
  • 15
  • 20