MCPcopy Create free account
hub / github.com/LFYSec/MScan / SimpleIndexer

Class SimpleIndexer

src/main/java/pascal/taie/util/SimpleIndexer.java:42–106  ·  view source on GitHub ↗

A simple map and list based implementation of Indexer. The indexes of the objects are same as their indexes in the list. If #getIndex(Object) is called with an object that was absent in this indexer, it will be added to the indexer automatically. If #getObject(int) is cal

Source from the content-addressed store, hash-verified

40 * {@code getIndex(o)}.
41 */
42public class SimpleIndexer<E> implements Indexer<E> {
43
44 private final Map<E, Integer> obj2index;
45
46 private final List<E> index2obj;
47
48 private int counter = 0;
49
50 /**
51 * Constructs an empty indexer.
52 */
53 public SimpleIndexer() {
54 this.obj2index = Maps.newMap();
55 this.index2obj = new ArrayList<>();
56 }
57
58 /**
59 * Constructs an empty mapper with the specified initial capacity.
60 */
61 public SimpleIndexer(int initialCapacity) {
62 this.obj2index = Maps.newMap(initialCapacity);
63 this.index2obj = new ArrayList<>(initialCapacity);
64 }
65
66 /**
67 * Constructs a mapper with a collection. The elements in the collection
68 * will be added to the new-created mapper.
69 */
70 public SimpleIndexer(Collection<? extends E> c) {
71 this(c.size());
72 c.forEach(this::getIndex);
73 }
74
75 @Override
76 public int getIndex(E o) {
77 Objects.requireNonNull(o, "null cannot be indexed");
78 Integer id = obj2index.get(o);
79 if (id == null) {
80 obj2index.put(o, counter);
81 index2obj.add(o);
82 return counter++;
83 } else {
84 return id;
85 }
86 }
87
88 @Override
89 public E getObject(int index) {
90 try {
91 return index2obj.get(index);
92 } catch (IndexOutOfBoundsException e) {
93 throw new IllegalArgumentException(
94 "index " + index + " was not mapped to any object", e);
95 }
96 }
97
98 @Override
99 public String toString() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected