Nov 27

Sometimes we need to shuffle the oder of elements in a list or array, like shuffling a deck of cards. The Collections utility class has a shuffle() method that achieves this for List’s, but what about arrays. There is no corresponding shuffle() method in the Arrays class, surely we don’t need to loop through the array.

Turns out the solution is very simple. We can just use the same method we use for shuffling lists after first creating a List representation of our array using Arrays.asList()

String[] array = {"A", "B", "C", "D", "E"};

written by objects \\ tags: , , , ,

Oct 23

Arrays in Java are actually Objects and sometimes we need to get the Class instance for an array object. An example would be when using reflection to get a method that takes an array as an argument.

Here’s an example for getting the Class instance for a string array.

Class arrayClass = String[].class;

written by objects \\ tags: , ,

Mar 04

Java provides a convenient Arrays.sort() method to sort an array of Object’s. The Objects in the array are required to implement the Comparable interface and the compareTo() method is used to compare Objects.

When an alternate sort order is needed you can do that using a Comparator which is passed to the sort() call.

The following example shows how you could sort an array of strings where the string contained a number (that should be sorted numerically) and a string (to be sorted alphabetically).

String[] array = new String[] { "34 abc", "123 dfd", "34 xyz", "12 xxx" };

Arrays.sort(array, new Comparator<String>() {

	public int compare(String s1, String s2) {
		// separate the number and string
		String[] tokens1 = s1.split(" ");
		String[] tokens2 = s2.split(" ");
		// compare the number from each item
		int compare = Integer.parseInt(tokens1[0]) - Integer.parseInt(tokens2[0]);
		// If number same compare the string
		return compare==0 ? tokens1[1].compareTo(tokens2[1]) : compare;

written by objects \\ tags: , , ,