Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java does not allow to extend array type

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?

like image 624
Abhishek Oza Avatar asked Jul 23 '14 14:07

Abhishek Oza


People also ask

Can arrays in Java be extended?

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.

Why does Java not allow generic arrays?

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.

Are arrays expandable?

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.

How do you extend the length of an array in Java?

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.


1 Answers

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:

  • You could put the logic into a helper class with static methods, similar to Collections, etc. or
  • You could encapsulate an array inside your IntArrayExtension class, and provide wrapper methods for accessing the array and its additional features.
like image 88
Sergey Kalinichenko Avatar answered Oct 01 '22 01:10

Sergey Kalinichenko