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

后端 未结 10 1454
故里飘歌
故里飘歌 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:10

    Using Java 8, you can simply use ncopies of Collections class:

    Object[] arrays = Collections.nCopies(size, object).stream().toArray();
    

    In your case it will be:

    Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
    .
    

    Here is a detailed answer of a similar case of yours.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 18:19

    It is also possible with Java 8 streams:

    int[] a = IntStream.generate(() -> value).limit(count).toArray();
    

    Probably, not the most efficient way to do the job, however.

    0 讨论(0)
  • 2020-12-12 18:22

    java.util.Arrays.fill()

    0 讨论(0)
  • 2020-12-12 18:26

    For Lists you can use

    Collections.fill(arrayList, "-")

    0 讨论(0)
  • 2020-12-12 18:30

    If it's a primitive type, you can use Arrays.fill():

    Arrays.fill(array, -1);
    

    [Incidentally, memset in C or C++ is only of any real use for arrays of char.]

    0 讨论(0)
提交回复
热议问题