I was going through Java documentation, and I learned that methods in the Arrays
class in Java are all static. I don't really understand the reason behind why they made it static.
For example, the following code violates the OO approach, because if I have a type, 'X', then all the methods which acts on it should be inside it:
int[] a = {34, 23, 12}; Arrays.sort(a);
It would be better if they have implemented the following way:
int[] a = {34, 23, 12}; a.sort();
Can anyone explain me a bit on this?
The Arrays class in java. util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class.
Advantages: Static members/methods are used as in helper classes say like Math or in constants classes. which helps other objects to utilize Strings or useful functions for which you do not need to create object but invoked using Class name. Example – singleton objects are invoked using a static function.
In Java, array is the most important data structure that contains elements of the same type. It stores elements in contiguous memory allocation. There are two types of array i.e. static array and dynamic array.
Static methods As discussed above, Any static member can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions: They can only directly call other static methods. They can only directly access static data.
In Java there is no way to extend the functionally of an array. Arrays all inherit from Object
but this gives very little. IMHO This is a deficiency of Java.
Instead, to add functionality for arrays, static utility methods are added to classes like Array
and Arrays
. These methods are static
as they are not instance methods.
Good observation. Observe also that not every array can be sorted. Only arrays of primitives and Objects which implement the Comparable
interface can be sorted. So a general sort()
method that applies to all arrays is not possible. And so we have several overloaded static methods for each of the supported types that are actually sortable.
@Holger correctly points out in the comments below that one of the overloaded static methods is indeed Arrays.sort(Object[])
but the docs explicitly state:
All elements in the array must implement the
Comparable
interface.
So it doesn't work for Objects that don't implement Comparable
or one of its subinterfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With