Java Array Cast

Posted: December 30th, 2011 | Author: admin | Filed under: Java | Tags: | No Comments »

Casting the array obtained by invoking the toArray() method on a collection yields a ClassCastException.
For example:

String[] strings = listOfStrings.toArray();

will throw the ClassCastException.
The trick is to use the overloaded version of toArray(), which takes an array as parameter. This the javadoc description of the method

toArray(T[] a)
“Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.”

The solution is therefore to do this:

String[] sv = (String[])v.toArray(new String[0]);

Non-ASCII chars in Java

Posted: November 29th, 2010 | Author: admin | Filed under: Uncategorized | Tags: , | No Comments »

If you are having problems with non-ASCII characters (for example the Danish æ, ø and å) not showing up correctly in your Java application, try giving the Java VM the following argument:

-Dfile.encoding=UTF-8

You can verify that the charset has been set with this statement:

Charset.defaultCharset();