001 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file 002 // for details. All rights reserved. Use of this source code is governed by a 003 // BSD-style license that can be found in the LICENSE file. 004 005 package com.google.dart.compiler.util; 006 007 import java.util.Collections; 008 import java.util.HashMap; 009 import java.util.Map; 010 011 /** 012 * Utility methods for operating on memory-efficient maps. All maps of size 0 or 013 * 1 are assumed to be immutable. All maps of size greater than 1 are assumed to 014 * be mutable. 015 */ 016 public class Maps { 017 private Maps() { 018 } 019 020 public static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) { 021 switch (map.size()) { 022 case 0: 023 // Empty -> Singleton 024 return Collections.singletonMap(key, value); 025 case 1: { 026 if (map.containsKey(key)) { 027 return Collections.singletonMap(key, value); 028 } 029 // Singleton -> HashMap 030 Map<K, V> result = new HashMap<K, V>(); 031 result.put(map.keySet().iterator().next(), map.values().iterator().next()); 032 result.put(key, value); 033 return result; 034 } 035 default: 036 // HashMap 037 map.put(key, value); 038 return map; 039 } 040 } 041 }