IntSet.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 * Marc R. Hoffmann - initial API and implementation
10 *
11 * $Id: $
12 *******************************************************************************/
13package org.jacoco.core.instr;
14
15import java.util.Arrays;
16
17/**
18 * Lightweight set of sorted int values. The implementation is designed for a
19 * small number of elements only.
20 *
21 * @author Marc R. Hoffmann
22 * @version $Revision: $
23 */
24final class IntSet {
25
26 private int[] store;
27
28 private int size;
29
30 /**
31 * Creates a new empty set with a initial capacity of 8 elements.
32 */
33 public IntSet() {
34 this(8);
35 }
36
37 /**
38 * Creates a new empty set with the given initial capacity.
39 *
40 * @param initialCapacity
41 * this is the initial capacity
42 */
43 public IntSet(final int initialCapacity) {
44 this.store = new int[initialCapacity];
45 this.size = 0;
46 }
47
48 /**
49 * Adds the given value to the set if it is not already contained.
50 *
51 * @param value
52 * value to add
53 * @return <code>true</code> if the value has actually been added
54 */
55 public boolean add(final int value) {
56 if (contains(value)) {
57 return false;
58 }
59 if (store.length == size) {
60 final int[] newStore = new int[size * 2];
61 System.arraycopy(store, 0, newStore, 0, size);
62 store = newStore;
63 }
64 store[size++] = value;
65 return true;
66 }
67
68 /**
69 * Clears all elements from the set.
70 */
71 public void clear() {
72 size = 0;
73 }
74
75 /**
76 * Tests whether the given value is in this set.
77 *
78 * @param value
79 * value to check
80 * @return <code>true</code> if the value is contained
81 */
82 public boolean contains(final int value) {
83 // search backwards as the last value is typically added again
84 for (int i = size; --i >= 0;) {
85 if (store[i] == value) {
86 return true;
87 }
88 }
89 return false;
90 }
91
92 /**
93 * Returns a sorted array of the current content.
94 *
95 * @return sorted array of the current content
96 */
97 public int[] toArray() {
98 final int[] result = new int[size];
99 System.arraycopy(store, 0, result, 0, size);
100 Arrays.sort(result);
101 return result;
102 }
103
104}