Okay, so that's a lot of questions and stuff to talk about but I'll see how much I can cover in a short answer.
Generics in Collection Declarations.
Let's start with reasons to use generics in your declarations rather than not using them.
Take the following two declarations;
HashMap hashmap = new HashMap();
HashMap<String,String> hashmap = new HashMap<String, String>();
The first will accept any key/value combinations and you will have to manually use instanceof
and casting to get the objects from the map because there is no guarantee that it will contain the object types you think it does.
The second uses generics in the declaration and ENSURES that only String
keys and values will make their way into your HashMap
instance at compile time. Also, when you call get()
, you will have a String
object returned automatically and will not have to check and cast it yourself. Unless you have a very good reason, you should always be using generics with your declarations.
Polymorphism in Collection Declarations.
Now onto polymorphism when declaring your collections. Take the following two examples;
List<String> sl = new ArrayList<String>();
ArrayList<String> sl2 = new ArrayList<String>();
The first is more flexible and could hold any custom List
subclass that any method decides to return. This means that methods such as get()
might return slightly different results depending on the List
subclass it contains, or that the items in the List
might be kept in a different order or such. Think about that for a moment. This gives you much greater flexibility but much fewer certainties.
If you absolutely want to make sure that your List
is an ArrayList
and so that variable's methods will always act in accordance to ArrayList
(and will always use insertion order), then use the second example. Otherwise if you want to allow some flexibility in List
type (for example if you want it to be able to take some ordered AND sorted lists) use the first.
I hope this helps, and I hope I didn't miss anything too important.
Here are some links for further reading from the official Java tutorials;