01: /*
02: * Copyright 2004 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.myfaces.shared_impl.util;
17:
18: import java.util.HashMap;
19: import java.util.Map;
20: import java.util.Set;
21: import java.util.Iterator;
22:
23: /**
24: * @author Anton Koinov (latest modification by $Author: prophecy $)
25: * @version $Revision: 388670 $ $Date: 2006-03-25 00:01:30 +0100 (Sa, 25 Mrz 2006) $
26: */
27: public class HashMapUtils {
28: //~ Constructors -------------------------------------------------------------------------------
29:
30: protected HashMapUtils() {
31: // block public access
32: }
33:
34: //~ Methods ------------------------------------------------------------------------------------
35:
36: /**
37: * Calculates initial capacity needed to hold <code>size</code> elements in
38: * a HashMap or Hashtable without forcing an expensive increase in internal
39: * capacity. Capacity is based on the default load factor of .75.
40: * <p>
41: * Usage: <code>Map map = new HashMap(HashMapUtils.calcCapacity(10));<code>
42: * </p>
43: * @param size the number of items that will be put into a HashMap
44: * @return initial capacity needed
45: */
46: public static final int calcCapacity(int size) {
47: return ((size * 4) + 3) / 3;
48: }
49:
50: /**
51: * Creates a new <code>HashMap</code> that has all of the elements
52: * of <code>map1</code> and <code>map2</code> (on key collision, the latter
53: * override the former).
54: *
55: * @param map1 the fist hashmap to merge
56: * @param map2 the second hashmap to merge
57: * @return new hashmap
58: */
59: public static HashMap merge(Map map1, Map map2) {
60: HashMap retval = new HashMap(calcCapacity(map1.size()
61: + map2.size()));
62:
63: retval.putAll(map1);
64: retval.putAll(map2);
65:
66: return retval;
67: }
68:
69: /**
70: * spit out each name/value pair
71: */
72: public static String mapToString(Map map) {
73: Set entries = map.entrySet();
74: Iterator iter = entries.iterator();
75: StringBuffer buff = new StringBuffer();
76: while (iter.hasNext()) {
77: Map.Entry entry = (Map.Entry) iter.next();
78: buff.append("[" + entry.getKey() + "," + entry.getValue()
79: + "]\n");
80: }
81: return buff.toString();
82: }
83:
84: }
|