Fill arrays with ranges of numbers

前端 未结 6 626
甜味超标
甜味超标 2020-11-29 06:20

Is there any syntax/package allowing quick filling of java arrays with ranges of numbers, like in perl?

e.g.

int[] arr = new int[1000];
arr=(1..500,3         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 06:50

    As for the first question, whether it is possible to fill an array with the values of a range: it is actually possible to achieve that with the combination of Range, DiscreteDomain, ContiguousSet and Ints from Guava:

    int[] array = Ints.toArray(
        ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers()));
    

    And, not exactly what is mentioned in the second part of the question, but it is possible to create a set with the elements of a range of a discrete domain:

    Set numbersFrom1To500 = 
        ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers());
    

    The resulting Set will not contain the specified elements physically, only logically (so it's memory footprint will be small), but can be iterated (since it's a Set):

    for (Integer integer : numbersFrom1To500) {
        System.out.println(integer);
    }
    

提交回复
热议问题