I'm trying to figure out how to check if the component type of an array implements Comparable, and if so, sort the array. Here's what I have:
if (prop1.getClass().isArray())
{
if (!(Array.getLength(prop1) == Array.getLength(prop2)))
throw new AssertionError(objectName + "." + propertyName + "'s aren't the same length!");
int len = Array.getLength(prop1);
if (0 == len)
return;
List list1 = Arrays.asList(prop1);
List list2 = Arrays.asList(prop2);
// class names of objects in arrays are weird
String componentClassName = StringUtils.remove(StringUtils.remove(list1.get(0).getClass().getName(), "[L"), ';');
Class componentClazz = null;
try
{
componentClazz = Class.forName(componentClassName);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
if (Comparable.class.isAssignableFrom(componentClazz))
{
Collections.sort(list1);
Collections.sort(list2);
The first sort throws an exception when prop1
is an array of String's:
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.Comparable
prop1
is type Object
, so Arrays.asList(prop1)
returns a list of one element, the object aka the array. When you then try to sort the list, it's rightfully complaining that the element (actually an array of something) is not Comparable
.
As for getting the array element type, you can't look at the first element, because it may be a subclass of the array element type. Just call prop1.getClass().getComponentType()
.
To sort an array, call one of the 8 overloads of Arrays.sort(a)
. Which one to call depends on the component type.
If you're not allowed to modify the original array, then clone it first.
Update
When I say "depends on the component type", I mean you have to check the type, and call the right version. Selecting a version of an overloaded method is done at compile-time, so it has to be done statically. (well, another layer of reflection is another choice)
Class<?> compType = prop1.getClass().getComponentType();
if (compType == int.class)
Arrays.sort((int[])prop1);
else if (compType == float.class)
Arrays.sort((float[])prop1);
// ... 5 more ...
else if (Comparable.class.isAssignableFrom(compType))
Arrays.sort((Comparable[])prop1);
else
throw new UnsupportedOperationException("Cannot sort array of " + compType.getName());