Sort two ints
Short answer: you cannot do this, java has no pointers.
But here is something similar that you can do:
public void swap(AtomicInteger a, AtomicInteger b){
You can do this with all kinds of container objects (for example, collections and arrays or custom objects with int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it one liner is with AtomicInteger, I think.
BTW: if your data is a list, the best way to share is to use Collections.swap(List, int, int) :
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.) Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.
Array Sort int []
Apparently, the real goal is to sort the array from int. This is single line with Arrays.sort(int[]) :
int[] arr = {2,3,1,378,19,25}; Arrays.sort(arr);
To check the output:
System.out.println(Arrays.toString(arr));
And here is a simple helper function to replace two positions in an ints array:
public static void swap(final int[] arr, final int pos1, final int pos2){ final int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; }
Sean Patrick Floyd Sep 02 '10 at 7:15 2010-09-02 07:15
source share