As an experiment, I tried to extend an int
-array like this:
public class IntArrayExtension extends int[]{
// additional fields and methods.
}
to add some methods related to sorting, swapping, sub-array building etc. in the class itself. But I got this error while compiling:
IntArrayExtension.java:1: unexpected type
found : int[]
required: class
public class IntArrayExtension extends int[]{
^
1 error
I am curious to know: why Java does not allow to extend an array?
Extending an array after initialization: As we can't modify the array size after the declaration of the array, we can only extend it by initializing a new array and copying the values of the old array to the new array, and then we can assign new values to the array according to the size of the array declared.
because the array is covariant which every type is a subclass of the object so this gives an error in run time due to casting exception. while the generic is invariant so when it builds on the type ensure or type-safe so if the type not like it creates type it gives a compiler error.
An array at its roots is a contiguous 'array' of memory. Other data can occupy data before and after this area of memory, hence it cannot be dynamically resized without allocating a new, different area of memory that fits the new, larger size.
Increase the Array Size Using the Arrays. copyOf() Method in Java. Java has a built-in copyOf() method that can create a new array of a larger size and copy our old array elements into the new one. The copyOf() function belongs to the Arrays class.
Extending a fundamental type such as a String
or an array opens up security holes. If Java let you extend an array, its methods that take arrays would become insecure. That is why strings are final
, and arrays cannot be extended at all.
For example, you could override the clone()
method, and return an array of incorrect size. This has a potential of breaking the logic of system code that takes an array as its parameter.
On top of that, arrays are special objects in Java, in that they do not have a class definition.
There are two solution to the problem that you are trying to solve:
Collections
, etc. orIntArrayExtension
class, and provide wrapper methods for accessing the array and its additional features.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