Something like that? Change As Jeddo noted, this structure cannot effectively remove elements. ArrayList + Set is easier if efficient removal is not required, so this structure is not very good for many.
import java.util.*; public class ArraySet<T> { private final Map<Integer, T> indexToElem; private final Map<T, Integer> elemToIndex; public ArraySet() { indexToElem = new HashMap<Integer, T>(); elemToIndex = new HashMap<T, Integer>(); } public T get(int index) { if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(); return indexToElem.get(index); } public void add(T elem) { if (!contains(elem)) { int index = indexToElem.size(); indexToElem.put(index, elem); elemToIndex.put(elem, index); } }
source share