barak manos
barak manos

Reputation: 30136

Java - sort a static array in the declaration line (instead of in a static constructor)

I have a class with a large static array of integers:

private static int[] array = {...};

I want to have it sorted without adding a static constructor, where I would call Arrays.sort(array).

On Python, I could simply write array = sorted([...]).

Questions:

  1. Is there any similar routine in Java, that I can use in a similar manner?

  2. Is there any other way for me to have the array sorted in the declaration line?

P.S.: It would also allow me to declare it final, which I would not be able to do otherwise.

Thanks

Upvotes: 1

Views: 261

Answers (5)

ach
ach

Reputation: 6234

Close to Ingo's solution, but I'd want to make sorted non-destructive:

public static int[] sorted(int [] arr) {
   int[] copy = new int[arr.length];
   System.arraycopy(arr, 0, copy, 0, arr.length);
   Arrays.sort(copy);
   return copy;
}

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53829

Simply:

private static final int[] array = mySort(new int[]{...})

private static int[] mySort(int[] a) {
    Arrays.sort(a);
    return a;
}

Upvotes: 2

McDowell
McDowell

Reputation: 108899

If you insist on avoiding static blocks/methods to no real benefit:

  private static final int[] foo = new Callable<int[]>() {
    public int[] call() {
      int[] arr = { 3, 2, 1 };
      Arrays.sort(arr);
      return arr;
    }
  }.call();

On the off-chance you're on Java 8:

private static final int[] foo = IntStream.of(3, 2, 1)
                                          .sorted()
                                          .toArray();

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234715

You can declare it final and still use a static initialiser:

private static final int[] array;

static {
    array = {...};
    Arrays.sort(array);
}

Upvotes: 5

Ingo
Ingo

Reputation: 36339

You must be missing something. You need to call a method at runtime to sort it, the compiler won't do it for you. But what exactly is the problem with:

final static int[] array = sorted( new int[] { ..... } );

which is quite the same as in Python. You just need a static method:

public static int[] sorted(int [] arr) {
    Array.sort(arr);
    return arr;
}

Upvotes: 0

Related Questions