Understanding generics and how collections use them

Generics can be confusing sometimes, a question most people don't ask themselves is why should I use them when polymophism should do just fine.  Here's a quick guide with code samples to illustrate the difference.  See the Generics and Comparables chapter in Head First Java.

A Node class built with generics

GitHub Example

I've programmed a simple Node class way too many times.  This one solves my problem when working with my coding examples, and is a GREAT example of generics.  Pay attention to the static methods, the first <T> defines the type, the next what we're returning, and finally the parameter. 

A Tree Node built with generics

GitHub Example

The next level of working with generics, ensure the type passed in implements the comparable interface.  

Collections and sorting with them

GitHub Example

This example illustrates that what you pass into a list needs to implement Collections interface to be sortable.  String already does this for you.  

Also demonstraits how to use a Comparitor to create a custom sorting object you can pass around.

Polymorphism vs Generics

GitHub Example

Here you'll see an instance where passing lists through polymorphism doesn't work.  Generics are intended to let you write type safe collections.  The idea is you won't be able to put a dog into a list of ducks.  Also notice how the wildcard ? accepts anything, but T extends Animal forces you to send something in that isA animal.  

Generic Class Examples

Java2Novice Examples

These examples are dead simple.  Now that we understand a little more about the why, check out the how.

Misc

Declairation of the Collections.sort() method, the type you send it must extend (or implement) Comparable and it's super must be of type t, it returns void and takes a list of type t...

  • public static <T extends Comparable<? super T>> void sort(List<T> list) {

In a generic declairation extends means extends this or can also means implements this, one word for both.

Hashcode and Equals

GitHub Example

This question always gets asked, what's the difference between hashcode and equals?  The example helps illustrate, that hashcode is used to group objects into buckets.  Equals is used to search that bucket for a match.  If two objects are equal, but have a different hash code, you're never going to find the second, you'll just match the first.

TreeSet

GitHub Example

In general, lists preserve order, sets ensure uniqueness, hash gives us key values.  You can get the best of both worlds (sorting and uniqueness) with TreeSet.  Just don't forget to implement Comparable on the objects.