0

Is there any good reason Arrays in Java do not extend Collection?

It seems like it would be useful to be able to test someObject instanceof Collection before iterating across it with for (Object element : someObject). Instead, from what I understand, the only way to know if an object is an array is to either use instanceof on every array type (Object[], int[], double[], ...) or to use someObject.getClass().isArray() but then this of course also forces a null check.

Aroto
  • 311
  • 1
  • 12
  • 1
    Short answer: arrays pre-date Collections, by a long measure. – vikingsteve Mar 28 '16 at 19:05
  • 2
    Questions of the form _"Why did the language designers make decision X"_ are really opinion based. The only concrete answers are to be found in the language specification (if the authors explained their choice) or by asking the designers directly. In this case it was likely a desire to accommodate existing concepts in a non-surprising way. – Jim Garrison Mar 28 '16 at 19:06
  • What's wrong with a null check? Or, even better, what's wrong with letting `someObject.getClass().isArray()` throw the `NullPointerException`? – Louis Wasserman Mar 28 '16 at 19:07

3 Answers3

0

Arrays in Java are implemented via specialized instructions in the JVM. They are separate first-class members of the system, and not classes in the conventional sense. They have to be in order to allow the specialized syntax that's used on arrays.

There are two special cases: null references and references to primitive arrays.

A null reference will cause instanceof to result false, while the isArray throws a NullPointerException.

Applied to a primitive array, the instanceof results false, but the isArray() returns true.

Dave Ranjan
  • 2,966
  • 24
  • 55
0

Actually there are many reason of it.

  • A collection is type-safe; an array is not. Because arrays "fake" covariance, ArrayStoreException can result at runtime

  • A list or set's equals, hashCode and toString methods do what users expect; those methods on an array do anything but what you expect -- a common source of bugs.

  • A collection can be thread-safe; even concurrent. An array is never safe to publish to multiple threads.

  • A collection can be mutable or immutable. A nonempty array must always be mutable.

For more detail follow please read : https://stackoverflow.com/a/6105705/1691223

Community
  • 1
  • 1
Shravan40
  • 8,922
  • 6
  • 28
  • 48
-1

Arrays are much more low-level than collections; some collections abstract over arrays (such as ArrayList or Vector), but native arrays are just a (protected, well-defined) memory block over which you can build you own abstraction.

Why is this a problem for you?

The foreach loop can also operate on arrays BTW, in which case it's just expanded into an indexed for expression.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40