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: , , , ,

Feb 05

The Arrays class has a set of helper toString methods for converting an array to a string representation.

String representation = Arrays.toString(array);

This will work for all array types. For Objects it uses the toString() method of the type to convert array elements.

If you need more control how the array is represented then you will need to implement the conversion yourself using a loop.

written by objects \\ tags: , , ,

Jan 30

The Arrays class includes methods for testing the equality of two array. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.

if (Arrays.equals(array1, array2))
  // array1 and array2 contain the same elements in the same order

written by objects \\ tags: , ,