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

Dec 21

Sometimes you need to store the stack trace from an exception in a String. A common approach is to use the printStackTrace() method to write it to a String which gives it to you in the same format as when you print it to stdout (or whereever)

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String trace = sw.toString();

Another option is to use the stack trace directly to create your string. This allows you to have full control over the format. For example you could use something as simple as the following:

String trace = Arrays.toString(ex.getStackTrace());

written by objects \\ tags: , , , ,