StringPool.java
1/*******************************************************************************
2 * Copyright (c) 2009, 2010 Mountainminds GmbH & Co. KG and Contributors
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Brock Janiczak - analysis and concept
10 * Marc R. Hoffmann - initial API and implementation
11 *
12 *******************************************************************************/
13package org.jacoco.core.analysis;
14
15import java.util.HashMap;
16import java.util.Map;
17
18/**
19 * Utility to normalize {@link String} instances in a way that if
20 * <code>equals()</code> is <code>true</code> for two strings they will be
21 * represented the same instance. While this is exactly what
22 * {@link String#intern()} does, this implementation avoids VM specific side
23 * effects and is supposed to be faster, as neither native code is called nor
24 * synchronization is required for concurrent lookup.
25 *
26 * @author Marc R. Hoffmann
27 * @version 0.4.1.20101007204400
28 */
29public final class StringPool {
30
31 private static final String[] EMPTY_ARRAY = new String[0];
32
33 private final Map<String, String> pool = new HashMap<String, String>(1024);
34
35 /**
36 * Returns a normalized instance that is equal to the given {@link String} .
37 *
38 * @param s
39 * any string or <code>null</code>
40 * @return normalized instance or <code>null</code>
41 */
42 public String get(final String s) {
43 if (s == null) {
44 return null;
45 }
46 final String norm = pool.get(s);
47 if (norm == null) {
48 pool.put(s, s);
49 return s;
50 }
51 return norm;
52 }
53
54 /**
55 * Returns a modified version of the array with all string slots normalized.
56 * It is up to the implementation to replace strings in the array instance
57 * or return a new array instance.
58 *
59 * @param arr
60 * String array or <code>null</code>
61 * @return normalized instance or <code>null</code>
62 */
63 public String[] get(final String[] arr) {
64 if (arr == null) {
65 return null;
66 }
67 if (arr.length == 0) {
68 return EMPTY_ARRAY;
69 }
70 for (int i = 0; i < arr.length; i++) {
71 arr[i] = get(arr[i]);
72 }
73 return arr;
74 }
75
76}