This Q is to look for a sample case where a generic array is absolutely necessary.
Generics and arrays "don't mix well".
Is there a case where a generic ArrayList won't do-- a generic array has no substitute and has to be used.
Effective Java leaves a door open for generic arrays saying that there may be cases where a generic array is necessary.
I've been using ArrayList without any shortcomings and can't think of a case like this.
TIA.
Note: i've seen these:
Along with some other discussions.
Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked.
If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.
Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.
All arrays implement the non-generic IList , ICollection and IEnumerable interfaces through their base class Array . This was the only reasonable way to give all arrays specific methods and interfaces, and is the primary use of the Array base class.
Some points:
If you have some "legacy" library then you're bound to the types that they use. This could be arrays.
If you handle native code then arrays will be a more natural way to exchange data with the native code.
If you access binary data (e.g. sound files or similar) then using an array can help.
If you handle big amount of binary data then an array could be more efficient.
So there are many reasons why an array could be helpful (especially with primitive types).
If you only handle objects then it is most times easier to use a List
.
I would say that Bloch meant convenient instead of necessary, arrays are simpler structures, easier to handle.
As a data structure, from a functionalities point of view, ArrayList
are interchangeable with array.
Arrays are obviously more lean memory-wise but require additional effort to get some basic functionalities (i.e. manual array resizing when the original array is not big enough to hold a new element) but other functions are already provided by the runtime (Arrays
class).
ArrayLists
are backed by actual Object
arrays so there isn't much difference performance wise, for common operations like searching and sorting (when using the same algorithm).
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