Advertisement
arch239

Untitled

Aug 27th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. import java.lang.reflect.Array;
  2. import java.util.Arrays;
  3.  
  4. class Main {
  5.     public static void main(String[] args) {
  6.         FastClearArray<Integer> a = new FastClearArray<>(Integer.class, 10);
  7.         System.out.println(a.put(1, 3) + " | " + a.get(2));
  8.         System.out.println(a.get(1) + " | " + a.get(2));
  9.         a.clearAll();
  10.         System.out.println(a.get(1) + " | " + a.put(2, 6));
  11.         System.out.println(a.put(1, 9) + " | " + a.get(2));
  12.         System.out.println(a.get(1) + " | " + a.get(2));
  13.         a.clearAll();
  14.         System.out.println(a.get(1) + " | " + a.get(2));
  15.     }
  16. }
  17.  
  18. public class FastClearArray<T> {
  19.  
  20.     private final T[] arr;
  21.     /**
  22.      * deceleration of masterModCount range exhaustion
  23.      */
  24.     private boolean modified;
  25.     /**
  26.      * aka modCount in Collections
  27.      * 18.5 sextillion of values - Hopefully, that's enough.
  28.      */
  29.     private long masterModCount = Long.MIN_VALUE;
  30.     private long[] modCount;
  31.  
  32.     public FastClearArray(Class<T> _class, int n) {
  33.         arr = (T[]) Array.newInstance(_class, n);
  34.         modCount = new long[n];
  35.         Arrays.fill(modCount, masterModCount);
  36.     }
  37.  
  38.     public T get(int index) {
  39.         return modCount[index] >= masterModCount
  40.                 ? arr[index]
  41.                 : null;
  42.     }
  43.  
  44.     public T put(int index, T value) {
  45.         T result = get(index);
  46.         arr[index] = value;
  47.  
  48.         modCount[index] = masterModCount;
  49.         modified = true;
  50.  
  51.         return result;
  52.     }
  53.  
  54.     public void clearAll() {
  55.         if (modified) {
  56.             masterModCount++;
  57.             modified = false;
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement