I\'m playing around with some code katas and trying to get a better understanding of java generics at the same time. I\'ve got this little method that prints arrays like I l
1 Can i avoid the cast to T in splitBottom and splitTop? It doesn't feel right, or I'm going about this the wrong way (don't tell me to use python or something .. ;) )
Not only can you not avoid it, but you shouldn't do it. In Java, different types of arrays are actually different runtime types. An array that was created as an Object[]
cannot be assigned to a variable of AnythingElse[]. The cast there will not fail immediately, because in generics the type T is erased, but later it will throw a ClassCastException when code tries it to use it as a Something[] as you promised them, but it is not.
The solution is to either use the Arrays.copyOf...
methods in Java 6 and later, or if you are using an earlier version of Java, use Reflection to create the correct type of array. For example,
T[] result = (T[])Array.newInstance(array.getClass().getComponentType(), size);
2 Do I have to write seperate methods to deal with primitive arrays or is there a better solution?
It is probably best to write separate methods. In Java, arrays of primitive types are completely separate from arrays of reference types; and there is no nice way to work with both of them.
It is possible to use Reflection to deal with both at the same time. Reflection has Array.get()
and Array.set()
methods that will work on primitive arrays and reference arrays alike. However, you lose type safety by doing this as the only supertype of both primitive arrays and reference arrays is Object
.