-3

there is any way to generate auto int array from 0 to 99

Example:

int [] nums = new int[99];

i want it like this:

int [] Nums = new int[] {0,1,2,3,4... ,99};

Thanks in advance <3 <3.

Abdelilah Elghazal
  • 61
  • 1
  • 1
  • 10

2 Answers2

1
 int [] nums = new int[99];
 for(int i = 0; i < nums.length; i++)
     nums[i] = i;

Other ways if you are using Java 8:

  • First technique

    int[] nums = IntStream.range(0, 99).toArray();

  • Second technique

    int[] nums = new int[99]; Arrays.setAll(nums, i -> i + 1);

Yuval Ben-Arie
  • 1,280
  • 9
  • 14
Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49
0

Combining Java 8 IntStream for an int range? and How to Convert a Java 8 Stream to an Array?:

IntStream.rangeClosed(0, 99).toArray(Integer[]::new);
daniu
  • 14,137
  • 4
  • 32
  • 53
  • 1
    An `Integer` array is not an `int` array. – khelwood Jul 21 '17 at 12:19
  • @khelwood I didn't test, but I thought that's why there is `toArray`... – Betlista Jul 21 '17 at 12:20
  • 2
    The OP asked for an `int` array, not an `Integer` array. `toArray(Integer[]::new)` will not even compile. It should be just `toArray()`. See [`IntStream.toArray()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#toArray--) – khelwood Jul 21 '17 at 12:24
  • Now I tested and You are correct. But `Integer::new` is ok in Java 8? – Betlista Jul 21 '17 at 12:25
  • It seems it might work somewhere, but `Integer[] arr = Integer[]::new;` shows compilation error "The target type of this expression must be a functional interface". – Betlista Jul 21 '17 at 12:28
  • @Betlista Integer[]::new is equivalent to i -> new Integer[i]. It's type is IntFunction, so you can't assign it to an Integer[]. – daniu Jul 21 '17 at 13:27