C graphics C graphics - 1 year ago 70
Java Question

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

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){

Answer Source

Out of curiosity, I have tested the performance of two versions of that method - one with a loop and the other one using guava:

public int[] loop() {
    int[] a = new int[100];
    for (int i = 0; i < 100; ++i) {
        a[i] = i;
    return a;

public int[] guava() {
    Set<Integer> set = ContiguousSet.create(Range.closed(0, 99), DiscreteDomains.integers());
    int[] a = Ints.toArray(set);
    return a;

Here are the results:

Benchmark     Mean     Mean error          Var    Units
guava      814.753         46.359     2034.726  nsec/op
loop        79.913          5.671       30.447  nsec/op

So the first method runs in 814 ns +/- 46ns vs. 80 ns +/- 5ns for the second one. So the loop is about 10x faster. If you call that method a few times, the 800 nanoseconds don't matter, if you call it very often, writing the loop is probably better.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download