0

Is there a way in Java to do something like:

int foo[] = new int[0..n];

i.e

foo[0] = 0

foo[3] = 3

1

3 Answers 3

3

Not using built-in language features. You can easily write a method to do it, of course, but there's nothing built-in - and I suspect that it's sufficiently rarely useful that it's not in many third party utility libraries (such as Guava) either.

Sign up to request clarification or add additional context in comments.

1 Comment

The closest Guava-based alternative is Range.closed(0, 3).asSet(DiscreteDomains.integers()).asList(). That's a mouthful, but that's because you really ought to just do it yourself.
2

I don't think so, but you could use a simple for-loop:

int foo[n];

for(int i = 0; i < n; i++) foo[i] = i;

And if you want a method try something like this:

public void initialize(int[] array, int start, int end) {
    int array_length = array.length;
    if (end > array_length) end = array_length;

    for (int i = start; i < end; i++) {
        array[i - start] = i;
    }
}

// In any other point in your code
int foo[] = new int[6];
initialize(foo, 0, 10);

Another way would be to make a Range class to add this functionality:

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Range implements Iterable<Integer> {
    Integer array[];

    public Range(int size) {
        this(0, size - 1);
    }

    public Range(int start, int end) {
        array = new Integer[end - start];

        for (int i = start; i < end; i++) {
            array[i - start] = i;
        }
    }

    public List<Integer> asList() {
        return Arrays.asList(array);
    }

    @Override
    public Iterator<Integer> iterator() {
        return Arrays.asList(array).iterator();
    }
}

Here is an usage example:

Range range = new Range(4, 10);

for (int i : range) {
    System.out.println(i);
}

I'm sure that this code can be improved but it isn't worth it.

2 Comments

+1, but that probably should be [n+1] and i <= n. At least, I'd expect that a notation like the OP's new int[0..n] would include both endpoints, 0 and n.
Yes, you are right, but would be easier to declare n as n+1 xD Anyway, is a simple example to say that what he is looking for is not possible. Thanks for your comment anyway ;)
1
int n = 10;
int[] arr = new int[n+1];

for loops has flexible syntax, so you can do even this:

for ( int i = 0; i < arr.length; arr[i] = i++ );

P.S.
If you want less code than above, you can do this:

int i = 0;
for ( int c : arr ) { arr[i] = i++; }

P.P.S.
Despite the fact that these pieces of code are laconic, for me they seems unclear, and smells bad.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.