0

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?

Balder
  • 8,623
  • 4
  • 39
  • 61
user3380123
  • 703
  • 1
  • 6
  • 14

2 Answers2

3

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

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.

ethanfar
  • 3,733
  • 24
  • 43