An example of how to use arrays in Java, how to sort the items and how to mix them
Code:
import java.util.*;
public class ArrayTest
{
public static void main (String [] args)
{
// Declare an array of String
String[] customers = {
"Arianne",
"Bill",
"David",
"Manuel",
"Veronic",
"Asia",
"Daniel",
"Renate",
"Vincent",
"Alexia"
};
Print(customers, "List of customers:");
// Order the array
Arrays.sort(customers);
Print(customers, "List of customers, after order:");
// Shuffle the array
Shuffle(customers);
Print(customers, "List of customers, after shuffle:");
System.exit(0);
}
// Print content of the array
private static void Print(String[] a, String t)
{
System.out.println( t );
for(int n=0; n<a.length; n++)
System.out.println("["+n+"] " + a[n] );
System.out.println( );
}
// Shuffle all elements of the array
private static void Shuffle(String[] a)
{
int n = a.length;
for (int i = 0; i < n; i++)
{
int s = i + (int) (Math.random() * (n-i));
Swap(a, i, s);
}
}
// Swap the content of two elements of the array
private static void Swap(String[] a, int i, int j)
{
String swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
Result:
>java -cp . ArrayTest
List of customers:
[0] Arianne
[1] Bill
[2] David
[3] Manuel
[4] Veronic
[5] Asia
[6] Daniel
[7] Renate
[8] Vincent
[9] Alexia
List of customers, after order:
[0] Alexia
[1] Arianne
[2] Asia
[3] Bill
[4] Daniel
[5] David
[6] Manuel
[7] Renate
[8] Veronic
[9] Vincent
List of customers, after shuffle:
[0] Manuel
[1] Bill
[2] Daniel
[3] Alexia
[4] Renate
[5] Veronic
[6] Asia
[7] Arianne
[8] Vincent
[9] David
>Exit code: 0