Possible Duplicate:
List versus ArrayList variable type?
I’m intialising a HashSet like so in my program:
Set<String> namesFilter = new HashSet<String>();
Is this functionally any different if I initilise like so?
HashSet<String> namesFilter = new HashSet<String>();
I’ve read this about the collections interface, and I understand interfaces (well, except their use here). I’ve read this excerpt from Effective Java, and I’ve read this SO question, but I feel none the wiser.
Is there a best practice in Java, and if so, why? My intuition is that it makes casting to a different type of Set easier in my first example. But then again, you’d only be casting to something that was a collection, and you could convert it by re-constructing it.
I think it’s better practice to use the interface over the concrete type, i.e.
By doing this, you commit yourself to only using the functionality provided by the
Setinterface. This makes it easier to swap out the kind of set you’re using at a later date if you decide that you want different performance characteristics (e.g. if you wanted to use aTreeSetinstead) without worrying about breaking your code.