-5

what is diference between using java and best use case I am not able to understand the difference b/w these two concepts can any body explain with example. What Java Collection should I use?

Map<string> map =new Hashmap<string>(); 
Hashmap<string> map =new Hashmap<string>();  

and which is better usage.

Note:can any one guide me best ebook for java collection and Data structure

Community
  • 1
  • 1

5 Answers5

3

For example, one difference is that if you want to change map later to be of another type that implements Map, you can't do that in the second example.

Fast example:

Map<Type> map = new HashMap<>();
map = new TreeMap<>(); //:)

HashMap<Type> map = new HashMap<>();
map = new TreeMap<>(); //:_(
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

With Map<String> map = new HashMap<String>(); you are using a simple form of dependency injection. Your code does't care if you are using a HashMap or a TreeMap because you can use their common interface. Later on if you want to change the map type you just have to do it on the variable declaration.

Lukas Eichler
  • 5,689
  • 1
  • 24
  • 43
0

Map is a interface, whereas HashMap is a concrete implementation of Map. Therefore the second construct will have functionality of HashMap and obviously has implemented Map.

However that being said, if you are passing this instance of Map to a function taking Map as an argument, than there will be not difference.

Sourabh Bhat
  • 1,793
  • 16
  • 21
0

There is no really best practice.

Use interface Map<string> map = new Hashmap<string>();:

  • Hide the concrete implementation algorithm
  • The most important is the interface, what you object can do not how it do it

Use concrete implementation Hashmap<string> map = new Hashmap<string>();:

  • Concrete implementation with all interface method and you can have some method specific to the implementation

After it's just a question of POO, i think the purist guys will only used interface because, it is more abstract and the concrete type (algorithm) can be easy updated.

But, in fact, create an interface for each type of class is really dirty for your project and create a multiple number of useless classes / interface. So it is not a good idea for me.

To conclude, i prefer to use what i really need. If it is important to stay generic, i use the interface Map, but in most case, i don't care of this and i prefer to be less abstract than possible for this container so i prefer to use HashMap.

In fact, it's more a troll and a discussion around a bear than a true response. Each developer has is own feeling of this.

Fabecc
  • 160
  • 4
0

Using the interface is always best practice unless you need to specify that a certain implementation of that interface must be used.

This is because it gives most flexibility for the future - increasing encapsulation by removing dependency on things that don't matter.

Tim B
  • 40,716
  • 16
  • 83
  • 128