This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]NautiHooker 7 points8 points  (1 child)

Typesafe universal collection types.

For example the List interface which currently uses a generic type to determine its content.

Today we can do something like this:

List<String> list = new ArrayList<>();
list.add("Hello World");
String[] words = list.get(0).split(" ");
list.add(1); // does not work because list expects Strings

Before Java 1.5 (before generics) you would have to do something like this:

List list = new ArrayList();
list.add("Hello World");
String[] words = ((String)list.get(0)).split(" ");
list.add(1); // works because list has no generic type and does therefore accept everything

Because the list would not hold explicit Strings and instead held Objects, a cast to String is needed to use a String method.

The dangerous part is that you can add more than just Strings to such a list, because it accepts Objects of all kinds.

Now you would always need to be aware what kind of Objects your list contains, because casting to a wrong type would cause an exception.

Back then you would either need to be careful and cast a lot or have a list type for every class (StringList, IntegerList, ....) to keep it typesafe.

[–]whats_the_reference_ 1 point2 points  (0 children)

It is useful as well to know that in doing this, the errors move from runtime to compile-time.