The introduction of generics has greatly improved code readability. Anyone who uses the code understands what types of inputs are essential for the integration efforts. For example, when Listing 3 is rewritten as Listing 4 below, the compiler throws errors during compilation.

Looking into the error, it is clear that you can add objects of type integer only. Errors like these make it easy for the developers to correct their mistakes.

Generics Wildcards

If you do not know what type of data your collection is holding, then you can use a wildcard (<?>) in the placeholder for generics to indicate that the data type is unknown.

Assuming you have an ArrayList that has elements of unknown data types, you can simply employ the wildcard and start using the ArrayList in your application. Typical usage will be something like Listing 5.

If you look carefully, the computeSum() method takes an argument of List, which is of unknown type, extending Number. The method is used for achieving the same action for both types (integer and double) of arguments. Using the unknown type is a little tricky and may not be clear in all your use cases. See the generics documentation for more information.

Good programming does not mean that you need to use complex development techniques. The simple, easy-to-understand code that you can produce with generics will be maintainable by others, which can make everyone's life easier when issues arise while you're not on premise. Others can debug your code easily in your absence.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.

Thanks for your registration, follow us on our social networks to keep up-to-date