SortIndex.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 *******************************************************************************/
12package org.jacoco.report.html.table;
13
14import java.util.ArrayList;
15import java.util.Collections;
16import java.util.Comparator;
17import java.util.List;
18
19/**
20 * A index on a list of items sorted with a given {@link Comparator}. The index
21 * does not change the list itself.
22 *
23 * @author Marc R. Hoffmann
24 * @version 0.4.1.20101007204400
25 * @param <T>
26 * type of the items
27 */
28final class SortIndex<T> {
29
30 private final Comparator<? super T> comparator;
31
32 private class Entry implements Comparable<Entry> {
33
34 final int idx;
35
36 final T item;
37
38 Entry(final int idx, final T item) {
39 this.idx = idx;
40 this.item = item;
41 }
42
43 public int compareTo(final Entry o) {
44 return comparator.compare(item, o.item);
45 }
46
47 }
48
49 private final List<Entry> list = new ArrayList<Entry>();
50
51 private int[] positions;
52
53 /**
54 * Creates a new index based in the given comparator.
55 *
56 * @param comparator
57 * comparator to sort items
58 */
59 public SortIndex(final Comparator<? super T> comparator) {
60 this.comparator = comparator;
61 }
62
63 /**
64 * Initializes the index for the given list of items.
65 *
66 * @param items
67 * list of items
68 */
69 public void init(final List<? extends T> items) {
70 this.list.clear();
71 int idx = 0;
72 for (final T i : items) {
73 final Entry entry = new Entry(idx++, i);
74 this.list.add(entry);
75 }
76 Collections.sort(list);
77 if (positions == null || positions.length < items.size()) {
78 positions = new int[items.size()];
79 }
80 int pos = 0;
81 for (final Entry e : this.list) {
82 positions[e.idx] = pos++;
83 }
84 }
85
86 /**
87 * Returns the sorted position of the element with the given index in the
88 * items list provided to the {@link #init(List)} method.
89 *
90 * @param idx
91 * index of a element of the list
92 * @return its position in a sorted list
93 */
94 public int getPosition(final int idx) {
95 return positions[idx];
96 }
97
98}