How to initialize all the elements of an array to any specific value in java

后端 未结 10 1456
故里飘歌
故里飘歌 2020-12-12 17:33

In C/C++ we have memset() function which can fulfill my wish but in Java how can i initialize all the elements to a specific value? Wh

10条回答
  •  攒了一身酷
    2020-12-12 18:17

    You could do this if it's short:

    int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

    but that gets bad for more than just a few.

    Easier would be a for loop:

      int[] myArray = new int[10];
      for (int i = 0; i < array.length; i++)
           myArray[i] = -1;
    

    Edit: I also like the Arrays.fill() option other people have mentioned.

提交回复
热议问题