Generics

Java Best Practices Series

Generics

26. Don’t Use Raw Types

Since Java 5, generics were introduced. However, before that Collections (e.g. List) where still part of the language.

With generics it became possible to declare, inside the diamond declaration (), which type a List would be working with. Without a diamond declaration, it would be classified as a raw type.

Because of backwards compatibility these raw types where not removed after java 5’s release. However, regardless of them being part of the language, they should never be used. 

Raw types enable the possibility to add unintended objects to the List, which will throw an exception at runtime.

27. Remove Unchecked Warnings

In relation to item 26, when a List has a diamond operator on the left-hand declaration, and no diamond operator (<>) on the right-hand initialization, it will produce a compile error.

Until Java 7, it was only possible to solve this by directly declaring which type of object the List would be working with inside a diamond declaration on the initialization.

However, after Java 7, it became possible to simply use the empty diamond operator, which would infer the type to the compiler.

28. Prefer Generics Lists Over Undefined Array Types.

If we were to simulate the same behavior as a generic List with an array, it would require a subclass array being assigned to a superclass array declaration.

Object[] array = new Long[];

Although this array provides some comparable features to a generic List, it is dangerous.

Now that the array has been defined as an Object array, any subclass of the Object-class, can be added. However, this is of cause not actually possible, and will fail at runtime.

On the other hand, a generic List, would instead fail on compile time. Thereby, giving you a warning before producing unreliable code.

29. Learn To Make Generic Classes

The JDK already provide several classes designed to work with generic types. This provides versatile classes, which can be used in multiple instances.

However, you should not limit yourself to the provided classes. It is just as useful to learn how to make your own generic classes.

30. Learn To Make Generic Methods

Similar to item 29, it is also valuable to learn how to make your own generic methods.

These generic methods could for example be used as a public static method in a utility class. Thereby, provide a versatile and accessible method for the entire project to utilize.

31. Use Bound Wildcards To Work With Subtypes Of Generic

When working with generics, the general idea is to declare which classtype a generic instance will be representing. However, declaring it as a normal generic (), does not enable the use of subtypes.

It is therefore recommended to use bound wildcards (<? extends E>) to declare compatibility with any subclass of the declared generic class.

32. Be Cautious When Using Varargs And Generics Together

When using varargs in combination with Generic types, it can often cause problems since the compiler might want to cast the generic objects to unsupported classes. (e.g. casting String[] to Object[])

Regardless of the dangers of working with the varargs and Generics, the language developers decided to keep it due to its versatile usability.

If the author of the method can verify for the safety of usage, it can be marked with the annotation @SafeVarargs.

33. Use Typesafe Containers

Generics can also be used to declare class specific behavior without providing any object instances as arguments.

E methodName(Class classType)

Providing direct references to the class can be used in many scenarios. For example, to alter the methods behavior, or to link the class container with an associated class instance.

public  void putFavorite(Class type, E instance) {
    favorites.put(Objects.requireNonNull(type), instance);
}

public E getFavorites(Class type) {
    return type.cast(favorites.get(type));
}

Recommended Reading

Books

About

Hi, I'm the Author

My name is Daniel H. Jacobsen and I’m a dedicated and highly motivated software developer with a masters engineering degree within the field of ICT. 

I have through many years of constantly learning and adapting to new challenges, gained a well-rounded understanding of what it takes to stay up to date with new technologies, tools and utilities. 

The purpose of this blog is to share both my learnings and knowledge with other likeminded developers as well as illustrating how these topics can be taught in a different and alternative manner.

If you like the idea of that, I would encourage you to sign up for the newsletter.

Cheers! 🍺

Didn't Find What You Were Looking For?

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Scroll to Top
INTEGU - Cookie-consent

INTEGU uses cookies to personalize your experience and provide traceability for affiliate links. By using the website, you agree to these terms and conditions. To learn more see the privacy policy page.