Changeset 15912 in josm for trunk/src/com/kitfox/svg/xml
- Timestamp:
- 2020-02-23T13:40:09+01:00 (5 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/com/kitfox/svg/xml/XMLParseUtil.java
r15904 r15912 38 38 39 39 import java.awt.Toolkit; 40 import java.lang.reflect.Method; 41 import java.util.Collections; 40 42 import java.util.HashMap; 41 43 import java.util.Iterator; 42 44 import java.util.LinkedList; 45 import java.util.Map; 43 46 import java.util.logging.Level; 44 47 import java.util.logging.Logger; … … 58 61 static final Matcher quoteMatch = Pattern.compile("^'|'$").matcher(""); 59 62 63 /** 64 * A reference to {@link Map#ofEntries(Map.Entry[])} available since Java 9 65 */ 66 static final Method mapOfEntries = mapOfEntriesMethod(); 67 68 private static Method mapOfEntriesMethod() { 69 try { 70 return Map.class.getMethod("ofEntries", Map.Entry[].class); 71 } catch (NoSuchMethodException e) { 72 return null; 73 } 74 } 75 60 76 /** Creates a new instance of XMLParseUtil */ 61 77 private XMLParseUtil() … … 300 316 * @param styleString - A CSS formatted string of styles. Eg, 301 317 * "font-size:12;fill:#d32c27;fill-rule:evenodd;stroke-width:1pt;" 302 * @param map - A map to which these styles will be added 303 */ 304 public static void parseStyle(String styleString, HashMap<String, String> map) { 318 * @return the map with the added styles 319 */ 320 public static Map<String, String> parseStyle(String styleString) { 321 final Map<String, String> map = new HashMap<>(); 305 322 final Pattern patSemi = Pattern.compile(";"); 306 323 … … 315 332 map.put(key, value); 316 333 }); 317 } 334 return toUnmodifiableMap(map); 335 } 336 337 /** 338 * Returns an unmodifiable map for the given map. 339 * Makes use of {@link Collections#emptyMap()} and {@link Collections#singletonMap} and {@link Map#ofEntries(Map.Entry[])} to save memory. 340 * 341 * @param map the map for which an unmodifiable map is to be returned 342 * @param <K> the type of keys maintained by this map 343 * @param <V> the type of mapped values 344 * @return an unmodifiable map 345 * @see <a href="https://dzone.com/articles/preventing-your-java-collections-from-wasting-memo"> 346 * How to Prevent Your Java Collections From Wasting Memory</a> 347 */ 348 @SuppressWarnings("unchecked") 349 public static <K, V> Map<K, V> toUnmodifiableMap(Map<K, V> map) { 350 if (map == null || map.isEmpty()) { 351 return Collections.emptyMap(); 352 } else if (map.size() == 1) { 353 final Map.Entry<K, V> entry = map.entrySet().iterator().next(); 354 return Collections.singletonMap(entry.getKey(), entry.getValue()); 355 } else if (mapOfEntries != null) { 356 try { 357 // Java 9: use Map.ofEntries(...) 358 return (Map<K, V>) mapOfEntries.invoke(null, new Object[]{map.entrySet().toArray(new Map.Entry[0])}); 359 } catch (Exception ignore) { 360 } 361 } 362 return Collections.unmodifiableMap(map); 363 } 364 318 365 }
Note:
See TracChangeset
for help on using the changeset viewer.