문제

Is order still guaranteed when the map objects are accessed as shown below at location 1 and 2?

    //.... 
    public void firstMethod(){
        Map<K,V> sortedMap=new LinkedHashMap<K,V>();
        sortedMap.put(h,g);
        //....

        Map<K,V> anotherMap=someOtherMethod(sortedMap);

        // order of anotherMap when read  ...2
    }

    public Map<K,V> someOtherMethod(Map<K,V> someMap){

         someMap.put(a,b);

         //order of someMap  when read ...1
         //.....

         return someMap;

    }
    //....
도움이 되었습니까?

해결책

If the concrete instance of your Map object is a LinkedHashMap yes. It does not matter what you do with it. The object will keep it's data ordered and the implementation does not change if you cast to just Map or even Object or pass it to methods. It will stay internally a LinkedHashMap. You might no longer see that it is one if you cast it to Object.

Assuming that you don't know the source code, the only thing that is not guaranteed is that someOtherMethod returns your LinkedHashMap. It could also re-order it.

A method should not be trusted unless it specifies those things. But since you know the sourcecode here, you have the guarantee that it is your LinkedHashMap in perferct order.

다른 팁

As per the docs:

Hash table and linked list implementation of the Map interface, with predictable iteration order.

So even after things are inserted and removed, the order should persist through whatever you want to do to it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top