Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.Array;
- import java.util.Arrays;
- class Main {
- public static void main(String[] args) {
- FastClearArray<Integer> a = new FastClearArray<>(Integer.class, 10);
- System.out.println(a.put(1, 3) + " | " + a.get(2));
- System.out.println(a.get(1) + " | " + a.get(2));
- a.clearAll();
- System.out.println(a.get(1) + " | " + a.put(2, 6));
- System.out.println(a.put(1, 9) + " | " + a.get(2));
- System.out.println(a.get(1) + " | " + a.get(2));
- a.clearAll();
- System.out.println(a.get(1) + " | " + a.get(2));
- }
- }
- public class FastClearArray<T> {
- private final T[] arr;
- /**
- * deceleration of masterModCount range exhaustion
- */
- private boolean modified;
- /**
- * aka modCount in Collections
- * 18.5 sextillion of values - Hopefully, that's enough.
- */
- private long masterModCount = Long.MIN_VALUE;
- private long[] modCount;
- public FastClearArray(Class<T> _class, int n) {
- arr = (T[]) Array.newInstance(_class, n);
- modCount = new long[n];
- Arrays.fill(modCount, masterModCount);
- }
- public T get(int index) {
- return modCount[index] >= masterModCount
- ? arr[index]
- : null;
- }
- public T put(int index, T value) {
- T result = get(index);
- arr[index] = value;
- modCount[index] = masterModCount;
- modified = true;
- return result;
- }
- public void clearAll() {
- if (modified) {
- masterModCount++;
- modified = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement