1

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.

Community
  • 1
  • 1
AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
  • I prefer using the interface. If you already know all the arguments, what's the question? What's the problem? – duffymo Oct 03 '12 at 09:40
  • See [What does it mean to “program to an interface”?](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Jesper Oct 03 '12 at 09:41
  • @duffymo I've heard the arguments, but they haven't helped me understand. The answer here and the answer in the proposed dupe make sense however. – AncientSwordRage Oct 03 '12 at 09:45

1 Answers1

6

I think it's better practice to use the interface over the concrete type, i.e.

Set<String> strings = new HashSet<String>();

By doing this, you commit yourself to only using the functionality provided by the Set interface. 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 a TreeSet instead) without worrying about breaking your code.

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154