Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

757
LINES

< > BotCompany Repo | #1012179 // SynchronizedArrayList - saves space over synchroList()

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (4360L/24K).

// Modified from java.util.ArrayList
 
sclass SynchronizedArrayList<A> extends SynchronizedArrayList_Base<A> implements RandomAccess, Cloneable {
  private static final int DEFAULT_CAPACITY = 10;
  private static final Object[] EMPTY_ELEMENTDATA = {};
  private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  transient Object[] elementData; // non-private to simplify nested class access
  private int size;

  *(int initialCapacity) {
      if (initialCapacity > 0) {
          this.elementData = new Object[initialCapacity];
      } else if (initialCapacity == 0) {
          this.elementData = EMPTY_ELEMENTDATA;
      } else {
          throw new IllegalArgumentException("Illegal Capacity: "+
                                             initialCapacity);
      }
  }

  *() {
      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  }

  *(Collection<? extends A> c) {
      elementData = c.toArray();
      if ((size = elementData.length) != 0) {
          // c.toArray might (incorrectly) not return Object[] (see 6260652)
          if (elementData.getClass() != Object[].class)
              elementData = Arrays.copyOf(elementData, size, Object[].class);
      } else {
          // replace with empty array.
          this.elementData = EMPTY_ELEMENTDATA;
      }
  }

  public synchronized void trimToSize() {
      modCount++;
      if (size < elementData.length) {
          elementData = (size == 0)
            ? EMPTY_ELEMENTDATA
            : Arrays.copyOf(elementData, size);
      }
  }

  public synchronized void ensureCapacity(int minCapacity) {
      int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
          // any size if not default element table
          ? 0
          // larger than default for default empty table. It's already
          // supposed to be at default size.
          : DEFAULT_CAPACITY;

      if (minCapacity > minExpand) {
          ensureExplicitCapacity(minCapacity);
      }
  }

  private void ensureCapacityInternal(int minCapacity) {
      if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
          minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
      }

      ensureExplicitCapacity(minCapacity);
  }

  private void ensureExplicitCapacity(int minCapacity) {
      modCount++;

      // overflow-conscious code
      if (minCapacity - elementData.length > 0)
          grow(minCapacity);
  }

  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

  private void grow(int minCapacity) {
      // overflow-conscious code
      int oldCapacity = elementData.length;
      int newCapacity = oldCapacity + (oldCapacity >> 1);
      if (newCapacity - minCapacity < 0)
          newCapacity = minCapacity;
      if (newCapacity - MAX_ARRAY_SIZE > 0)
          newCapacity = hugeCapacity(minCapacity);
      // minCapacity is usually close to size, so this is a win:
      elementData = Arrays.copyOf(elementData, newCapacity);
  }

  private static int hugeCapacity(int minCapacity) {
      if (minCapacity < 0) // overflow
          throw new OutOfMemoryError();
      return (minCapacity > MAX_ARRAY_SIZE) ?
          Integer.MAX_VALUE :
          MAX_ARRAY_SIZE;
  }

  public synchronized int size() {
      return size;
  }

  public synchronized boolean isEmpty() {
      return size == 0;
  }

  public boolean contains(Object o) {
      return indexOf(o) >= 0;
  }

  public synchronized int indexOf(Object o) {
      if (o == null) {
          for (int i = 0; i < size; i++)
              if (elementData[i]==null)
                  return i;
      } else {
          for (int i = 0; i < size; i++)
              if (o.equals(elementData[i]))
                  return i;
      }
      return -1;
  }

  public synchronized int lastIndexOf(Object o) {
      if (o == null) {
          for (int i = size-1; i >= 0; i--)
              if (elementData[i]==null)
                  return i;
      } else {
          for (int i = size-1; i >= 0; i--)
              if (o.equals(elementData[i]))
                  return i;
      }
      return -1;
  }

  public synchronized Object clone() {
    ret new SynchronizedArrayList(this);
  }

  public synchronized Object[] toArray() {
      return Arrays.copyOf(elementData, size);
  }

  @SuppressWarnings("unchecked")
  public synchronized  <T> T[] toArray(T[] a) {
      if (a.length < size)
          // Make a new array of a's runtime type, but my contents:
          return (T[]) Arrays.copyOf(elementData, size, a.getClass());
      System.arraycopy(elementData, 0, a, 0, size);
      if (a.length > size)
          a[size] = null;
      return a;
  }

  // Positional Access Operations

  @SuppressWarnings("unchecked")
  A elementData(int index) {
      return (A) elementData[index];
  }

  public synchronized A get(int index) {
      rangeCheck(index);

      return elementData(index);
  }

  public synchronized A set(int index, A element) {
      rangeCheck(index);

      A oldValue = elementData(index);
      elementData[index] = element;
      return oldValue;
  }

  public synchronized boolean add(A e) {
      ensureCapacityInternal(size + 1);  // Increments modCount!!
      elementData[size++] = e;
      return true;
  }

  public synchronized void add(int index, A element) {
      rangeCheckForAdd(index);

      ensureCapacityInternal(size + 1);  // Increments modCount!!
      System.arraycopy(elementData, index, elementData, index + 1,
                       size - index);
      elementData[index] = element;
      size++;
  }

  public synchronized A remove(int index) {
      rangeCheck(index);

      modCount++;
      A oldValue = elementData(index);

      int numMoved = size - index - 1;
      if (numMoved > 0)
          System.arraycopy(elementData, index+1, elementData, index,
                           numMoved);
      elementData[--size] = null; // clear to let GC do its work

      return oldValue;
  }

  public synchronized boolean remove(Object o) {
      if (o == null) {
          for (int index = 0; index < size; index++)
              if (elementData[index] == null) {
                  fastRemove(index);
                  return true;
              }
      } else {
          for (int index = 0; index < size; index++)
              if (o.equals(elementData[index])) {
                  fastRemove(index);
                  return true;
              }
      }
      return false;
  }

  private void fastRemove(int index) {
      modCount++;
      int numMoved = size - index - 1;
      if (numMoved > 0)
          System.arraycopy(elementData, index+1, elementData, index,
                           numMoved);
      elementData[--size] = null; // clear to let GC do its work
  }

  public synchronized void clear() {
      modCount++;

      // clear to let GC do its work
      for (int i = 0; i < size; i++)
          elementData[i] = null;

      size = 0;
  }

  public synchronized boolean addAll(Collection<? extends A> c) {
      Object[] a = c.toArray();
      int numNew = a.length;
      ensureCapacityInternal(size + numNew);  // Increments modCount
      System.arraycopy(a, 0, elementData, size, numNew);
      size += numNew;
      return numNew != 0;
  }

  public synchronized boolean addAll(int index, Collection<? extends A> c) {
      rangeCheckForAdd(index);

      Object[] a = c.toArray();
      int numNew = a.length;
      ensureCapacityInternal(size + numNew);  // Increments modCount

      int numMoved = size - index;
      if (numMoved > 0)
          System.arraycopy(elementData, index, elementData, index + numNew,
                           numMoved);

      System.arraycopy(a, 0, elementData, index, numNew);
      size += numNew;
      return numNew != 0;
  }

  public synchronized void removeRange(int fromIndex, int toIndex) {
      modCount++;
      int numMoved = size - toIndex;
      System.arraycopy(elementData, toIndex, elementData, fromIndex,
                       numMoved);

      // clear to let GC do its work
      int newSize = size - (toIndex-fromIndex);
      for (int i = newSize; i < size; i++) {
          elementData[i] = null;
      }
      size = newSize;
  }

  private void rangeCheck(int index) {
      if (index >= size)
          throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  }

  private void rangeCheckForAdd(int index) {
      if (index > size || index < 0)
          throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  }

  /**
   * Constructs an IndexOutOfBoundsException detail message.
   * Of the many possible refactorings of the error handling code,
   * this "outlining" performs best with both server and client VMs.
   */
  private String outOfBoundsMsg(int index) {
      return "Index: "+index+", Size: "+size;
  }

  public synchronized boolean removeAll(Collection<?> c) {
      Objects.requireNonNull(c);
      return batchRemove(c, false);
  }

  public synchronized boolean retainAll(Collection<?> c) {
      Objects.requireNonNull(c);
      return batchRemove(c, true);
  }

  private boolean batchRemove(Collection<?> c, boolean complement) {
      final Object[] elementData = this.elementData;
      int r = 0, w = 0;
      boolean modified = false;
      try {
          for (; r < size; r++)
              if (c.contains(elementData[r]) == complement)
                  elementData[w++] = elementData[r];
      } finally {
          // Preserve behavioral compatibility with AbstractCollection,
          // even if c.contains() throws.
          if (r != size) {
              System.arraycopy(elementData, r,
                               elementData, w,
                               size - r);
              w += size - r;
          }
          if (w != size) {
              // clear to let GC do its work
              for (int i = w; i < size; i++)
                  elementData[i] = null;
              modCount += size - w;
              size = w;
              modified = true;
          }
      }
      return modified;
  }

  /**
   * Save the state of the <tt>ArrayList</tt> instance to a stream (that
   * is, serialize it).
   *
   * @serialData The length of the array backing the <tt>ArrayList</tt>
   *             instance is emitted (int), followed by all of its elements
   *             (each an <tt>Object</tt>) in the proper order.
   */
  private void writeObject(java.io.ObjectOutputStream s)
      throws java.io.IOException{
      // Write out element count, and any hidden stuff
      int expectedModCount = modCount;
      s.defaultWriteObject();

      // Write out size as capacity for behavioural compatibility with clone()
      s.writeInt(size);

      // Write out all elements in the proper order.
      for (int i=0; i<size; i++) {
          s.writeObject(elementData[i]);
      }

      if (modCount != expectedModCount) {
          throw new ConcurrentModificationException();
      }
  }

  private void readObject(java.io.ObjectInputStream s)
      throws java.io.IOException, ClassNotFoundException {
      elementData = EMPTY_ELEMENTDATA;

      // Read in size, and any hidden stuff
      s.defaultReadObject();

      // Read in capacity
      s.readInt(); // ignored

      if (size > 0) {
          // be like clone(), allocate array based upon size not capacity
          ensureCapacityInternal(size);

          Object[] a = elementData;
          // Read in all elements in the proper order.
          for (int i=0; i<size; i++) {
              a[i] = s.readObject();
          }
      }
  }

  /**
   * Returns a list iterator over the elements in this list (in proper
   * sequence), starting at the specified position in the list.
   * The specified index indicates the first element that would be
   * returned by an initial call to {@link ListIterator#next next}.
   * An initial call to {@link ListIterator#previous previous} would
   * return the element with the specified index minus one.
   *
   * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
   *
   * @throws IndexOutOfBoundsException {@inheritDoc}
   */
  public synchronized ListIterator<A> listIterator(int index) {
      if (index < 0 || index > size)
          throw new IndexOutOfBoundsException("Index: "+index);
      return new ListItr(index);
  }

  /**
   * Returns a list iterator over the elements in this list (in proper
   * sequence).
   *
   * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
   *
   * @see #listIterator(int)
   */
  public ListIterator<A> listIterator() {
      return new ListItr(0);
  }

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   *
   * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
   *
   * @return an iterator over the elements in this list in proper sequence
   */
  public Iterator<A> iterator() {
      return concurrentlyIterateList(this);
  }

  /**
   * An optimized version of AbstractList.Itr
   */
  private class Itr implements Iterator<A> {
      int cursor;       // index of next element to return
      int lastRet = -1; // index of last element returned; -1 if no such
      int expectedModCount = modCount;

      public boolean hasNext() {
          return cursor != size;
      }

      @SuppressWarnings("unchecked")
      public A next() {
          checkForComodification();
          int i = cursor;
          if (i >= size)
              throw new NoSuchElementException();
          Object[] elementData = SynchronizedArrayList.this.elementData;
          if (i >= elementData.length)
              throw new ConcurrentModificationException();
          cursor = i + 1;
          return (A) elementData[lastRet = i];
      }

      public void remove() {
          if (lastRet < 0)
              throw new IllegalStateException();
          checkForComodification();

          try {
              SynchronizedArrayList.this.remove(lastRet);
              cursor = lastRet;
              lastRet = -1;
              expectedModCount = modCount;
          } catch (IndexOutOfBoundsException ex) {
              throw new ConcurrentModificationException();
          }
      }

      final void checkForComodification() {
          if (modCount != expectedModCount)
              throw new ConcurrentModificationException();
      }
  }

  /**
   * An optimized version of AbstractList.ListItr - TODO: replace with concurrent iterator or synchronize
   */
  private class ListItr extends Itr implements ListIterator<A> {
      ListItr(int index) {
          super();
          cursor = index;
      }

      public boolean hasPrevious() {
          return cursor != 0;
      }

      public int nextIndex() {
          return cursor;
      }

      public int previousIndex() {
          return cursor - 1;
      }

      @SuppressWarnings("unchecked")
      public A previous() {
          checkForComodification();
          int i = cursor - 1;
          if (i < 0)
              throw new NoSuchElementException();
          Object[] elementData = SynchronizedArrayList.this.elementData;
          if (i >= elementData.length)
              throw new ConcurrentModificationException();
          cursor = i;
          return (A) elementData[lastRet = i];
      }

      public void set(A e) {
          if (lastRet < 0)
              throw new IllegalStateException();
          checkForComodification();

          try {
              SynchronizedArrayList.this.set(lastRet, e);
          } catch (IndexOutOfBoundsException ex) {
              throw new ConcurrentModificationException();
          }
      }

      public void add(A e) {
          checkForComodification();

          try {
              int i = cursor;
              SynchronizedArrayList.this.add(i, e);
              cursor = i + 1;
              lastRet = -1;
              expectedModCount = modCount;
          } catch (IndexOutOfBoundsException ex) {
              throw new ConcurrentModificationException();
          }
      }
  }

  public List<A> subList(int fromIndex, int toIndex) {
      _subListRangeCheck(fromIndex, toIndex, size);
      return new SubList(this, 0, fromIndex, toIndex);
  }

  private class SubList extends SynchronizedArrayList_Base<A> implements RandomAccess {
      private final SynchronizedArrayList_Base<A> parent;
      private final int parentOffset;
      private final int offset;
      int size;

      SubList(SynchronizedArrayList_Base<A> parent,
              int offset, int fromIndex, int toIndex) {
          this.parent = parent;
          this.parentOffset = fromIndex;
          this.offset = offset + fromIndex;
          this.size = toIndex - fromIndex;
          this.modCount = SynchronizedArrayList.this.modCount;
      }

      public A set(int index, A e) { synchronized(SynchronizedArrayList.this) {
          rangeCheck(index);
          checkForComodification();
          A oldValue = SynchronizedArrayList.this.elementData(offset + index);
          SynchronizedArrayList.this.elementData[offset + index] = e;
          return oldValue;
      }}

      public A get(int index) { synchronized(SynchronizedArrayList.this) {
          rangeCheck(index);
          checkForComodification();
          return SynchronizedArrayList.this.elementData(offset + index);
      }}

      public int size() { synchronized(SynchronizedArrayList.this) {
          checkForComodification();
          return this.size;
      }}

      public void add(int index, A e) { synchronized(SynchronizedArrayList.this) {
          rangeCheckForAdd(index);
          checkForComodification();
          parent.add(parentOffset + index, e);
          this.modCount = parent.modCount();
          this.size++;
      }}

      public A remove(int index) { synchronized(SynchronizedArrayList.this) {
          rangeCheck(index);
          checkForComodification();
          A result = parent.remove(parentOffset + index);
          this.modCount = parent.modCount();
          this.size--;
          return result;
      }}

      public void removeRange(int fromIndex, int toIndex) { synchronized(SynchronizedArrayList.this) {
          checkForComodification();
          parent.removeRange(parentOffset + fromIndex,
                             parentOffset + toIndex);
          this.modCount = parent.modCount();
          this.size -= toIndex - fromIndex;
      }}

      public boolean addAll(Collection<? extends A> c) {
          return addAll(this.size, c);
      }

      public boolean addAll(int index, Collection<? extends A> c) { synchronized(SynchronizedArrayList.this) {
          rangeCheckForAdd(index);
          int cSize = c.size();
          if (cSize==0)
              return false;

          checkForComodification();
          parent.addAll(parentOffset + index, c);
          this.modCount = parent.modCount();
          this.size += cSize;
          return true;
      }}

      public Iterator<A> iterator() {
          return listIterator();
      }

      public ListIterator<A> listIterator(final int index) { synchronized(SynchronizedArrayList.this) {
          checkForComodification();
          rangeCheckForAdd(index);
          final int offset = this.offset;

          return new ListIterator<A>() {
              int cursor = index;
              int lastRet = -1;
              int expectedModCount = SynchronizedArrayList.this.modCount;

              public boolean hasNext() {
                  return cursor != SubList.this.size;
              }

              @SuppressWarnings("unchecked")
              public A next() {
                  checkForComodification();
                  int i = cursor;
                  if (i >= SubList.this.size)
                      throw new NoSuchElementException();
                  Object[] elementData = SynchronizedArrayList.this.elementData;
                  if (offset + i >= elementData.length)
                      throw new ConcurrentModificationException();
                  cursor = i + 1;
                  return (A) elementData[offset + (lastRet = i)];
              }

              public boolean hasPrevious() {
                  return cursor != 0;
              }

              @SuppressWarnings("unchecked")
              public A previous() {
                  checkForComodification();
                  int i = cursor - 1;
                  if (i < 0)
                      throw new NoSuchElementException();
                  Object[] elementData = SynchronizedArrayList.this.elementData;
                  if (offset + i >= elementData.length)
                      throw new ConcurrentModificationException();
                  cursor = i;
                  return (A) elementData[offset + (lastRet = i)];
              }

              public int nextIndex() {
                  return cursor;
              }

              public int previousIndex() {
                  return cursor - 1;
              }

              public void remove() {
                  if (lastRet < 0)
                      throw new IllegalStateException();
                  checkForComodification();

                  try {
                      SubList.this.remove(lastRet);
                      cursor = lastRet;
                      lastRet = -1;
                      expectedModCount = SynchronizedArrayList.this.modCount;
                  } catch (IndexOutOfBoundsException ex) {
                      throw new ConcurrentModificationException();
                  }
              }

              public void set(A e) {
                  if (lastRet < 0)
                      throw new IllegalStateException();
                  checkForComodification();

                  try {
                      SynchronizedArrayList.this.set(offset + lastRet, e);
                  } catch (IndexOutOfBoundsException ex) {
                      throw new ConcurrentModificationException();
                  }
              }

              public void add(A e) {
                  checkForComodification();

                  try {
                      int i = cursor;
                      SubList.this.add(i, e);
                      cursor = i + 1;
                      lastRet = -1;
                      expectedModCount = SynchronizedArrayList.this.modCount;
                  } catch (IndexOutOfBoundsException ex) {
                      throw new ConcurrentModificationException();
                  }
              }

              final void checkForComodification() {
                  if (expectedModCount != SynchronizedArrayList.this.modCount)
                      throw new ConcurrentModificationException();
              }
          };
      }}

      public List<A> subList(int fromIndex, int toIndex) { synchronized(SynchronizedArrayList.this) {
          _subListRangeCheck(fromIndex, toIndex, size);
          return new SubList(parent, offset, fromIndex, toIndex);
      }}

      private void rangeCheck(int index) {
          if (index < 0 || index >= this.size)
              throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
      }

      private void rangeCheckForAdd(int index) {
          if (index < 0 || index > this.size)
              throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
      }

      private String outOfBoundsMsg(int index) {
          return "Index: "+index+", Size: "+this.size;
      }

      private void checkForComodification() {
          if (SynchronizedArrayList.this.modCount != this.modCount)
              throw new ConcurrentModificationException();
      }
  }

  @Override
  @SuppressWarnings("unchecked")
  public synchronized void sort(Comparator<? super A> c) {
      final int expectedModCount = modCount;
      Arrays.sort((A[]) elementData, 0, size, c);
      if (modCount != expectedModCount) {
          throw new ConcurrentModificationException();
      }
      modCount++;
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, ydilcnlqtmvn

No comments. add comment

Snippet ID: #1012179
Snippet name: SynchronizedArrayList - saves space over synchroList()
Eternal ID of this version: #1012179/15
Text MD5: e53e5aa7bc42f942f2782236603360d6
Transpilation MD5: 490abd71d95c9860471b0dd9ba03d3c7
Author: stefan
Category: javax / collections
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-07-24 02:34:45
Source code size: 24601 bytes / 757 lines
Pitched / IR pitched: No / No
Views / Downloads: 523 / 1951
Version history: 14 change(s)
Referenced in: [show references]