arrays, Array and Arrays

Overview.

Java is an OO language but it doesn't have a specific array type which is the parent of all arrays. This means that arrays inherit their methods from the Object class. Unfortunately, the default methods for Object are now very useful, so there are Two helper utility classes Array and Arrays. If arrays has a proper parent type, it could implement these methods.

What methods do arrays have and what are they good for?

method use
getClass() Can be use to call getComponentType(), but has limited use in itself. Note: the generic type will be Class<?> regardless of whether you think the compiler should know this type or not.
hashCode() This is not the hashCode of the contents of the array but the internal id of the array. Given that arrays are mutable, this is a safe but not always what you want. If arrays had an immutable version, it could do what Arrays.hashCode() does.
equals() Again the contents is not compared, but only whether this is the same object. For immutable array, Arrays.equals() can be used.
clone() Useful for arrays, but you have to cast the return type. This is because Java has no This return type or similar,.
toString() This prints the internal class name and the internal id. Almost always useless.
notify(), notifyAll(), wait(), wait(long), wait(long, int) Arrays are not a good choice for locks or locking. Cells in an array are not volatile even if the refer to it is.
finalize() Always does nothing for an array.

By comparison, Array & Arrays define around 100 public utility methods, with names like equals(), hashCode(), and toString() It supports all variations of primitive arrays and object array. This is the sort of thing you would do in a non-OO language like C.

What is the parent class of arrays?

The parent class of object arrays is Object[]. This class does not add any extra functionality but can be informative. Unfortunately if you have a primitive array the parent is Object, so it is not safe to cast to (Object[]) for all arrays, only Object is safe, but says nothing really. (Only that an array is not a primitive)

How could it be different?

Arrays could have a parent interface for mutable arrays and an additional one for immutable arrays.
These classes could use all the methods in Arrays and Array.
Two methods could be added to either take a mutable copy or immutable copy of an array.

Conclusion.

An array is neither a primitive nor a well implemented Class. I believe this could be added, by providing a number of interfaces which give access to polymorphic implementations of methods such as equals, hashCode, toString, sort, binarySearch, set, get, fill.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.