PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to preserve order of insertion in Map.of factory?

 September 20, 2022     factory-method, hashmap, java, java-9     No comments   

Issue

Java 9 offers Map.of() feature to easily create a map with fixed values.

Problem: I want to create a map that preserves order of insertion like LinkedHashMap. Is that possible with that factory? At least map.of() does not preserv the order...


Solution

There isn't a factory method like LinkedHashMap::of indeed, and a Map does not have an order per-se, so the only way I see it is to build a LinkedHashMap if you really needed one.

Btw from the JEP itself:

Static factory methods on concrete collection classes (e.g., ArrayList, HashSet) have been removed from this proposal ...

There is another wrinkle, which is that static methods on classes are inherited by subclasses. Suppose a static factory method HashMap.of() were to be added. Since LinkedHashMap is a subclass of HashMap, it would be possible for application code to call LinkedHashMap.of(). This would end up calling HashMap.of(), not at all what one would expect!

Point here is that static methods are inherited, but not overridable, thus if such a method would have been added to HashMap it could have not been overridden in LinkedHashMap.

If you can use guava, you could use ImmutableMap that is documented as:

An immutable, hash-based Map with reliable user-specified iteration order...



Answered By - Eugene
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing