Is the iteration order for various representations of the collection of this Map a consistent guarantee?

For this type of Map are there guarantees that the iteration over Collection views returned by keySet , values and entries methods is repeated in the same order?

Background: I wonder if there will be a conversion

 public static void doSomethingForEachEntry(Map<String, Integer> someMap) { for (String key : someMap.keySet()) { doSomething(someMap.get(key)); } } 

to

 public static void doSomethingForEachEntry(Map<String, Integer> someMap) { for (Integer value : someMap.values()) { doSomething(value); } } 

it is guaranteed that the iteration order does not change.

+5
source share
2 answers

Although it is true that you cannot rely on a specific order if the Map implementation does not explicitly define this, there is a proposal in the API documentation, which implies the existence of a single common order for the map and all its types of collection:

the display order is defined as the order in which iterators in the map collection views return their elements.

(my emphasis)

In order for this to be done, the map has its own order (even if it cannot be indicated and can change when the map is changed), and all collection views must correspond to this order. Regardless of whether this is a guarantee, and in particular, whether all third-party card implementations will be respected, this is another question.

It is also worth noting that they are explicitly defined in the Map interface as representations that are supported by the map (for example, if you remove an element from keySet , the corresponding Map must be removed from the map). This means that in reality it is less likely that you will get different orders from the correct Map implementation than it would be if you made small copies of the collection views.

Having said all this, if the question is: "Is this a safe refactor?" then the answer is yes, until the source code breaks itself. "If the method depends on a specific order and, therefore, on a specific implementation of Map , the method should be declared to accept only this type of Map . Otherwise, you have a potential temporary bomb if the base Map implementation will change down the line (and I saw how a real software crash occurred due to this with the JDK update).

If a particular caller relies on a specific order because he knows that he is transmitting an ordered implementation of Map , that’s fine, and that order will be saved after your refactor.

+7
source

The iteration order depends on the specific implementation of the Map you are using. If you know the type of card, refer to the documentation. If you do not, do not rely on any order of iterations.

0
source

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


All Articles