@@ -135,6 +135,24 @@ public String toString() {
135135 */
136136 private final Map <String , Object > map ;
137137
138+ /**
139+ * An internal factory method that can be overridden if the
140+ * user desires JSONObject to use a specific map type.
141+ * <p>
142+ * The default is HashMap to ensure that elements are unordered per the specification.
143+ * JSON tends to be a portable transfer format that allows container
144+ * implementations to rearrange their items for faster element
145+ * retrieval based on associative access.
146+ * Therefore, an implementation ought not rely on the order of items.
147+ * @param capacity starting capacity. If < 0 then use the default capacity/constructor
148+ * @return a new Map
149+ */
150+ protected Map <String , Object > newInternalMap (int capacity ) {
151+ if (capacity < 0 )
152+ return new HashMap <>();
153+ return new HashMap <>(capacity );
154+ }
155+
138156 /**
139157 * Retrieves the type of the underlying Map in this class.
140158 *
@@ -156,13 +174,7 @@ public Class<? extends Map> getMapType() {
156174 * Construct an empty JSONObject.
157175 */
158176 public JSONObject () {
159- // HashMap is used on purpose to ensure that elements are unordered by
160- // the specification.
161- // JSON tends to be a portable transfer format to allows the container
162- // implementations to rearrange their items for a faster element
163- // retrieval based on associative access.
164- // Therefore, an implementation mustn't rely on the order of the item.
165- this .map = new HashMap <String , Object >();
177+ this .map = newInternalMap (-1 );
166178 }
167179
168180 /**
@@ -324,9 +336,9 @@ private JSONObject(Map<?, ?> m, int recursionDepth, JSONParserConfiguration json
324336 throw new JSONException ("JSONObject has reached recursion depth limit of " + jsonParserConfiguration .getMaxNestingDepth ());
325337 }
326338 if (m == null ) {
327- this .map = new HashMap < String , Object >( );
339+ this .map = newInternalMap (- 1 );
328340 } else {
329- this .map = new HashMap < String , Object > (m .size ());
341+ this .map = newInternalMap (m .size ());
330342 for (final Entry <?, ?> e : m .entrySet ()) {
331343 if (e .getKey () == null ) {
332344 throw new NullPointerException ("Null key." );
@@ -525,7 +537,7 @@ public JSONObject(String baseName, Locale locale) throws JSONException {
525537 * @param initialCapacity initial capacity of the internal map.
526538 */
527539 protected JSONObject (int initialCapacity ){
528- this .map = new HashMap < String , Object > (initialCapacity );
540+ this .map = newInternalMap (initialCapacity );
529541 }
530542
531543 /**
0 commit comments