Advertisement
Guest User

StrictArray 1.1

a guest
Jul 7th, 2015
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.NoSuchElementException;
  2.  
  3. /**
  4.  * @author I_Support_KKK
  5.  * @since 1.8
  6.  * @version 1.1
  7.  *
  8.  *          StrictArray is a high-performance, compact, non-duplicate array
  9.  *          utility which, as its name implies, is strict on its range which
  10.  *          needs to be supplied. To allocate a new StrictArray, the method
  11.  *          "newStrictArray" will need to be invoked.
  12.  */
  13. public final class StrictArray<T> {
  14.  
  15.     private final Object[] array;
  16.  
  17.     private int current;
  18.  
  19.     private StrictArray(final int size) {
  20.         if (size <= 0) {
  21.             throw new IllegalArgumentException("invalid size");
  22.         }
  23.         this.array = new Object[size];
  24.     }
  25.  
  26.     public static <T> StrictArray<T> newStrictArray(final int size) {
  27.         return new StrictArray<>(size);
  28.     }
  29.  
  30.     public void add(final T obj) {
  31.         if (this.contains(obj)) {
  32.             return;
  33.         }
  34.         if (this.current > this.array.length) {
  35.             throw new ArrayStoreException("array is full");
  36.         }
  37.         this.array[this.current++] = obj;
  38.     }
  39.  
  40.     public void remove(final T obj) {
  41.         this.array[this.indexOf(obj)] = null;
  42.     }
  43.  
  44.     @SuppressWarnings("unchecked")
  45.     public T get(final int index) {
  46.         return (T) this.array[index];
  47.     }
  48.  
  49.     public int indexOf(final T obj) {
  50.         if (!this.contains(obj)) {
  51.             throw new NoSuchElementException(String.format("element '%s' doesn't exist", obj.toString()));
  52.         }
  53.         for (int index = 0; index < this.array.length; index++) {
  54.             if (this.array[index] == obj) {
  55.                 return index;
  56.             }
  57.         }
  58.         return -1;
  59.     }
  60.  
  61.     public boolean contains(final T obj) {
  62.         return this.indexOf(obj) >= 0;
  63.     }
  64.  
  65.     public boolean isEmpty() {
  66.         return this.array.length == 0;
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement