Reputation: 30136
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:
Is there any similar routine in Java, that I can use in a similar manner?
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
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
Reputation: 53829
Simply:
private static final int[] array = mySort(new int[]{...})
private static int[] mySort(int[] a) {
Arrays.sort(a);
return a;
}
Upvotes: 2
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
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
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