Creating a Collection Instance in JAVA

Possible duplicate:
Why do I need an interface for a Java class?
What is the advantage of polymorphism using the Collection interface to create an ArrayList?

In many examples, I see that when creating an instance of some collection, such as TreMap, it uses it as a type:

Map<String,String> theMap = new TreeMap<String,String>(); 

Why not use

 TreeMap<String,String> theMap = new TreeMap<String,String>(); 
+4
source share
5 answers

Because it is considered best practice for coding an interface (Map) instead of implementing (TreeMap). This way, you can switch to another implementation (for example, HashMap, if later you decide that this is the best solution) with minimal code points.

+5
source

As a rule, it is better to code the interface rather than the implementation, which allows you to change the implementation without having to change the code that refers to it.

The only time it’s wise not to do this is when the code uses the characteristics of a particular implementation. For example, if this code requires access to the fast indexing element of an ArrayList , it might make sense to force a certain implementation.

+3
source

In general, it is better to program with Interfaces because it is easier, eg, to switch from TreeMap (in order) to HashMap (possibly faster).

If you use interfaces when possible, you only need to change one part of the source code.

+1
source

Reason The Liskov substitution principle . Directly quoted what was said.

Let q (x) be a property provable about objects x of type T. Then q (y) must be provable for objects y of type S, where S is a subtype of T.

Simple explanation

  • Map is an interface
  • And interface is a contract

By using Map we confirm that we are using a contract of what Map should do.

for instance

  • doSomething(Map<String, String> map)
  • doSomething(TreeMap<String, String> map)

doSomething(Map<String, String> map) allows you to use any implementation that confirms the Map contract, which allows you to work with any of the subtypes.

Does doSomething(TreeMap<String, String> map) accept any subtype of TreeMap . But TreeMap not a contract, so any subtype of TreeMap can violate its signature / behavior (methods actually). Thus, making TreeMap less preferred than Map . An inheritance composition can give you more information about this.

+1
source

This is one of the best Java schemes: a program that uses interfaces, if you can.

This helps make the application more flexible, since the method that receives this map can also work with other implementations of Map, but the method that received TreeMap can only use TreeMap and its children.

Thus, you get the freedom to change your working methods if you find that HashMap will improve the speed of your application.

0
source

Source: https://habr.com/ru/post/1379154/


All Articles