• Post Reply Bookmark Topic Watch Topic
  • New Topic

Map's keySet()  RSS feed

 
Ranch Hand
Posts: 96
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


On line 7, keySet() method returns a Set instance . Since a set may not maintain the original order, is it possible that the order in lines 6 and 7 may differ sometimes ? in this example it doesn't. but is it possible in any other case ? since a Set is created with the given elements of the map , and is returned,  order might change right ?
 
Marshal
Posts: 4051
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally for a Map your suspicion would be correct. By definition of the Map interface the items in it are not ordered, and by definition of the Set interface its items are also not ordered.

But....

The TreeMap implementation of the Map interface maintains element order by its keys. In addition, the TreeMap implementation of keySet() returns an implementation of Set that also maintains order by its values, i.e. the Map keys. All of these details are contained in the JavaDoc for TreeMap which which you could have answered your own question. Familiarity with the JavaDoc is a great resource to keep in your tool kit.
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
keySet() returns a backing view. That means it should reflect the contents of the map as accurately as possible, including the order of the keys. I don't know of any Map that has a key set with a different order.
 
Lilou Laure
Ranch Hand
Posts: 96
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Cooke wrote:Normally for a Map your suspicion would be correct. By definition of the Map interface the items in it are not ordered, and by definition of the Set interface its items are also not ordered.

But....

The TreeMap implementation of the Map interface maintains element order by its keys. In addition, the TreeMap implementation of keySet() returns an implementation of Set that also maintains order by its values, i.e. the Map keys. All of these details are contained in the JavaDoc for TreeMap which which you could have answered your own question. Familiarity with the JavaDoc is a great resource to keep in your tool kit.


Ok so I guess if I used HashMap , a HashSet implementation would be returned , and if I used a TreeMap, a TreeSet implementation would be returned , etc.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Changes to the set must be reflected in the map. Regular set implementations can't do that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!