Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shortest way of filling an array with 1,2...n

Tags:

java

arrays

Is there anything as quick as this in java? ( quick in coding)

int [] a = {1..99}; 

or I have to go for this:

int [] a=new int[100]; for (int i=0;i <100;++i){ a[i]=i; } 
like image 875
C graphics Avatar asked Apr 15 '13 16:04

C graphics


People also ask

How do you short an array?

To sort Short array, use the Arrays. sort() method. Let us first declare and initialize an unsorted Short array. short[] arr = new short[] { 35, 25, 18, 45, 77, 21, 3 };

What is the shortest way to declare and create an array?

int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

How do you make an array of size n?

Given a number N, the task is to create an array arr[] of size N, where the value of the element at every index i is filled according to the following rules: arr[i] = ((i – 1) – k), where k is the index of arr[i – 1] that has appeared second most recently.


2 Answers

Since Java 8 this is possible:

int[] a = IntStream.range(1, 100).toArray(); 

(And shorter than the other java 8 answer .).

like image 115
Bachi Avatar answered Sep 16 '22 17:09

Bachi


Another alternative if you use Java 8:

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

The lambda expression accepts the index of the cell, and returns a value to put in that cell. In this case, cells 0 - 99 are assigned the values 1-100.

like image 21
Manos Nikolaidis Avatar answered Sep 17 '22 17:09

Manos Nikolaidis