Was type safety the only reason to introduce generics for the java.util.Collection
classes, so the addition of heterogeneous elements in a Collection
is prevented? Or have there been other reasons too?

- 8,623
- 4
- 39
- 61

- 703
- 1
- 6
- 14
-
Why are you asking? Is it just of curiosity or there is some other reason too? – Andrew Logvinov Mar 23 '14 at 08:00
-
1Because it's redundant to write `List` for `Integer`, then `List` for `String`, then for `Double`, then for...... – Maroun Mar 23 '14 at 08:01
-
1@AndrewLogvinov just curiosity – user3380123 Mar 23 '14 at 08:02
-
2@MarounMaroun no I don't think so,they wrote it for object,so redundancy is not the reason – user3380123 Mar 23 '14 at 08:04
-
possible duplicate of [What are Generics in Java?](http://stackoverflow.com/questions/7815528/what-are-generics-in-java) – Joe Mar 23 '14 at 08:41
-
Because the type system was incomplete without it. – user207421 Mar 23 '14 at 08:52
2 Answers
I'd say that the reason is that most use-cases require a collection of just one class, or one class and its subclasses. For those use-cases, it is convenient to have a type-safe collection where you don't need to typecast the keys / values / entries extracted from the respective collections.
Use-cases where you genuinely need a "collection of any object" are unusual. But these use-cases are supported by using a ?
as the collection type parameter; e.g.
List<Object> listOfAnything = new ArrayList<>();
Clearly, generics do not prevent heterogeneous collections. But if you want homogeneous collections, generics allow you to do this conveniently and with type-safety.

- 698,415
- 94
- 811
- 1,216
Generics were introduced to the Java language to increase the type safety.
Say you have a list of items, to which you are only adding instances of class A:
List list = new LinkedList();
list.add(new A());
list.add(new A());
...
When you want to use some of the objects you entered the list, you do something like:
A a1 = (A) list.get(0);
A a2 = (A) list.get(1);
...
However, nothing prevents anyone from doing the following:
list.add(new NonA());
which will result in you getting a ClassCastException in your code. This is because the types are being checked in run time not in compilation time.
Enter generics, which allow you to do the following:
List<A> list = new LinkedList<A>();
list.add(new A());
list.add(new A());
...
And now, if anyone tries the following:
list.add(new NonA());
They will get a compilation error, thus preventing this error.

- 3,733
- 24
- 43