Member-only story

Effective Java! Don’t Use Raw Types

Kyle Carter
4 min readMay 13, 2021

This chapter starts a new section of Effective Java about generics. Before Java 5 where generics were introduced to the language, retrieving items from a collection required a cast of the object being returned. Thankfully, in modern Java, we don’t need to deal with this anymore and can use generics to provide us type safety as well as cleaner code.

Let’s briefly go over the definition of a generic in Java. A generic is a class or interface that has one or more type parameters. The way that this ends up looking is the class or interface name followed by angled brackets with the actual type in it. So an example of this would be List<String> myList = .... Each generic type also has a raw type which is simply the generic type without the actual type called out so the raw type of the previous example would simply be: List myList = .... Raw types act as if all the type information is erased and these exist for compatibility reasons. It is the relationship between generic types and raw types that this chapter is about.

Before generics existed in Java if you wanted a collection and add some object to it you would do something like the following:

Collection myStampCollection = ...;myStampCollection.add(new Stamp(...));myStampCollection.add(new Coin(...));(Stamp)myStampCollection.get(1);

Uh oh, looks like I made a mistake. The above code will compile without much issue (other than a vague warning) but at…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet