1

I recently started learning about JAVA generics. Everything made sense and I kinda understand them now. But one thing bugged me out - you cannot create array of the generic type.

I wanted to implement Abstract Data Types such as queue and stack, but with some generic type as the underlying data stored in the stack. How would I get around that ? I am sure I am missing but what it is ?

Thanks in advance.

Evdzhan Mustafa
  • 3,126
  • 1
  • 20
  • 37

2 Answers2

4

Effective Java, CHAPTER 5 GENERICS, Item 25: Prefer lists to arrays:

Arrays differ from generic types in two important ways. First, arrays are covariant. This scary-sounding word means simply that if Sub is a subtype of Super, then the array type Sub[] is a subtype of Super[]. Generics, by contrast, are invariant: for any two distinct types Type1 and Type2, List<Type1> is neither a subtype nor a supertype of List<Type2> ...

The second major difference between arrays and generics is that arrays are reified [JLS, 4.7]. This means that arrays know and enforce their element types at runtime. As noted above, if you try to store a String into an array of Long, you’ll get an ArrayStoreException. Generics, by contrast, are implemented by erasure [JLS, 4.6]. This means that they enforce their type constraints only at compile time and discard (or erase) their element type information at runtime. Erasure is what allows generic types to interoperate freely with legacy code that does not use generics (Item 23). Because of these fundamental differences, arrays and generics do not mix well. For example, it is illegal to create an array of a generic type, a parameterized type, or a type parameter. None of these array creation expressions are legal: new List[], new List[], new E[]. All will result in generic array creation errors at compile time.

Long story short: Arrays and Generics have kind of "opposite" characteristics which makes it very difficult, if not impossible in some situations, to mix them, so better take Joshua Bloch's word on it and use Lists instead of arrays when generics are involves .

Nir Alfasi
  • 49,889
  • 11
  • 75
  • 119
-3

Arrays can not be generic in Java.

On the other hand you already have Stack, Queue, Set, Map and other collection types — just examine java.util.* or do some research about Java Collections Framework.

Cromax
  • 1,369
  • 1
  • 18
  • 29
  • I know that there is a library, but I want to try and implement those classes my self. Just to get a feeling of how those ADT work. – Evdzhan Mustafa Feb 09 '14 at 20:57
  • 1
    Arrays can be generic: http://stackoverflow.com/questions/529085/how-to-generic-array-creation They are just different from the other generic types – Svetlin Zarev Feb 09 '14 at 21:08
  • It's not a generic array, it's generic class which casts array of objects to a generic type. It's something else than generics. Besides it's also dangerous. In the post you gave there's even explanation on this. – Cromax Feb 09 '14 at 21:22