CopyOnWriteArrayList.java

Index Score
net.sf.l2j.util
L2J

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
DOC_COMMENTNumber of javadoc comment lines
COMMENTSComment lines
LOOPSNumber of loops
JAVA0143JAVA0143 Synchronized method
DECL_COMMENTSComments in declarations
RETURNSNumber of return points from functions
CYCLOMATICCyclomatic complexity
INTERFACE_COMPLEXITYInterface complexity
LINESNumber of lines in the source file
SIZESize of the file in bytes
FUNCTIONSNumber of function declarations
JAVA0035JAVA0035 Missing braces in for statement
COMPARISONSNumber of comparison operators
LOCLines of code
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
LOGICAL_LINESNumber of statements
PARAMSNumber of formal parameter declarations
OPERATORSNumber of operators
ELOCEffective lines of code
PROGRAM_LENGTHHalstead program length
OPERANDSNumber of operands
BLOCKSNumber of blocks
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
UNIQUE_OPERANDSNumber of unique operands
PROGRAM_VOCABHalstead program vocabulary
JAVA0145JAVA0145 Tab character used in source file
JAVA0036JAVA0036 Missing braces in while statement
EXEC_COMMENTSComments in executable code
JAVA0282JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
LINE_COMMENTNumber of line comments
UNIQUE_OPERATORSNumber of unique operators
JAVA0150JAVA0150 java.lang.Error (or subclass) thrown
WHITESPACENumber of whitespace lines
JAVA0117JAVA0117 Missing javadoc: method 'method'
EXITSProcedure exits
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0109JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0256JAVA0256 Assignment of external collection/array to field
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
/* File: CopyOnWriteArrayList.java Written by Doug Lea. Adapted and released, under explicit permission, from JDK1.2 ArrayList.java which carries the following copyright: * Copyright 1997 by Sun Microsystems, Inc., * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information * of Sun Microsystems, Inc. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with Sun. History: Date Who What 21Jun1998 dl Create public version 9Oct1999 dl faster equals 29jun2001 dl Serialization methods now private */ package net.sf.l2j.util; import java.util.*; /** * This class implements a variant of java.util.ArrayList in which all mutative * operations (add, set, and so on) are implemented by making a fresh copy of * the underlying array. * <p> * This is ordinarily too costly, but it becomes attractive when traversal * operations vastly overwhelm mutations, and, especially, when you cannot or * don't want to synchronize traversals, yet need to preclude interference among * concurrent threads. The iterator method uses a reference to the state of the * array at the point that the iterator was created. This array never changes * during the lifetime of the iterator, so interference is impossible. (The * iterator will not traverse elements added or changed since the iterator was * created, but usually this is a desirable feature.) * <p> * As much code and documentation as possible was shamelessly copied from * java.util.ArrayList (Thanks, Josh!), with the intent of preserving all * semantics of ArrayList except for the copy-on-write property. (The java.util * collection code could not be subclassed here since all of the existing * collection classes assume elementwise mutability.) * <p> * Because of the copy-on-write policy, some one-by-one mutative operations in * the java.util.Arrays and java.util.Collections classes are so time/space * intensive as to never be worth calling (except perhaps as benchmarks for * garbage collectors :-). * <p> * Three methods are supported in addition to those described in List and * ArrayList. The addIfAbsent and addAllAbsent methods provide Set semantics for * add, and are used in CopyOnWriteArraySet. However, they can also be used * directly from this List version. The copyIn method (and a constructor that * invokes it) allow you to copy in an initial array to use. This method can be * useful when you first want to perform many operations on a plain array, and * then make a copy available for use through the collection API. * <p> * Due to their strict read-only nature, element-changing operations on * iterators (remove, set, and add) are not supported. These are the only * methods throwing UnsupportedOperationException. * <p> * <p>[ <a * href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> * Introduction to this package. </a>] * * @see CopyOnWriteArraySet */ public class CopyOnWriteArrayList implements List, Cloneable, java.io.Serializable { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3763093076863955507L; /** * The held array. Directly access only within synchronized methods */ protected transient Object[] array_; /** * Accessor to the array intended to be called from within unsynchronized * read-only methods */ protected synchronized Object[] array() { return array_; } /** * Constructs an empty list * */ public CopyOnWriteArrayList() { array_ = new Object[0]; } /** * Constructs an list containing the elements of the specified Collection, * in the order they are returned by the Collection's iterator. */ public CopyOnWriteArrayList(Collection c) { array_ = new Object[c.size()]; Iterator i = c.iterator(); int size = 0; while (i.hasNext()) array_[size++] = i.next(); } /** * Create a new CopyOnWriteArrayList holding a copy of given array * * @param toCopyIn * the array. A copy of this array is used as the internal array. */ public CopyOnWriteArrayList(Object[] toCopyIn) { copyIn(toCopyIn, 0, toCopyIn.length); } /** * Replace the held array with a copy of the <code>n</code> elements of * the provided array, starting at position <code>first</code>. To copy * an entire array, call with arguments (array, 0, array.length). * * @param toCopyIn * the array. A copy of the indicated elements of this array is * used as the internal array. * @param first * The index of first position of the array to start copying * from. * @param n * the number of elements to copy. This will be the new size of * the list. */ public synchronized void copyIn(Object[] toCopyIn, int first, int n) { array_ = new Object[n]; System.arraycopy(toCopyIn, first, array_, 0, n); } /** * Returns the number of components in this list. * * @return the number of components in this list. */ public int size() { return array().length; } /** * Tests if this list has no components. * * @return <code>true</code> if this list has no components; * <code>false</code> otherwise. */ public boolean isEmpty() { return size() == 0; } /** * Returns true if this list contains the specified element. * * @param o * element whose presence in this List is to be tested. */ public boolean contains(Object elem) { Object[] elementData = array(); int len = elementData.length; return indexOf(elem, elementData, len) >= 0; } /** * Searches for the first occurence of the given argument, testing for * equality using the <code>equals</code> method. * * @param elem * an object. * @return the index of the first occurrence of the argument in this list; * returns <code>-1</code> if the object is not found. * @see Object#equals(Object) */ public int indexOf(Object elem) { Object[] elementData = array(); int len = elementData.length; return indexOf(elem, elementData, len); } /** * static version allows repeated call without needed to grab lock for array * each time */ protected static int indexOf(Object elem, Object[] elementData, int len) { if (elem == null) { for (int i = 0; i < len; i++) if (elementData[i] == null) return i; } else { for (int i = 0; i < len; i++) if (elem.equals(elementData[i])) return i; } return -1; } /** * Searches for the first occurence of the given argument, beginning the * search at <code>index</code>, and testing for equality using the * <code>equals</code> method. * * @param elem * an object. * @param index * the index to start searching from. * @return the index of the first occurrence of the object argument in this * List at position <code>index</code> or later in the List; * returns <code>-1</code> if the object is not found. * @see Object#equals(Object) */ // needed in order to compile on 1.2b3 public int indexOf(Object elem, int index) { Object[] elementData = array(); int elementCount = elementData.length; if (elem == null) { for (int i = index; i < elementCount; i++) if (elementData[i] == null) return i; } else { for (int i = index; i < elementCount; i++) if (elem.equals(elementData[i])) return i; } return -1; } /** * Returns the index of the last occurrence of the specified object in this * list. * * @param elem * the desired component. * @return the index of the last occurrence of the specified object in this * list; returns -1 if the object is not found. */ public int lastIndexOf(Object elem) { Object[] elementData = array(); int len = elementData.length; return lastIndexOf(elem, elementData, len); } protected static int lastIndexOf(Object elem, Object[] elementData, int len) { if (elem == null) { for (int i = len - 1; i >= 0; i--) if (elementData[i] == null) return i; } else { for (int i = len - 1; i >= 0; i--) if (elem.equals(elementData[i])) return i; } return -1; } /** * Searches backwards for the specified object, starting from the specified * index, and returns an index to it. * * @param elem * the desired component. * @param index * the index to start searching from. * @return the index of the last occurrence of the specified object in this * List at position less than index in the List; -1 if the object is * not found. */ public int lastIndexOf(Object elem, int index) { // needed in order to compile on 1.2b3 Object[] elementData = array(); if (elem == null) { for (int i = index; i >= 0; i--) if (elementData[i] == null) return i; } else { for (int i = index; i >= 0; i--) if (elem.equals(elementData[i])) return i; } return -1; } /** * Returns a shallow copy of this list. (The elements themselves are not * copied.) * * @return a clone of this list. */ public Object clone() { try { Object[] elementData = array(); CopyOnWriteArrayList v = (CopyOnWriteArrayList) super.clone(); v.array_ = new Object[elementData.length]; System.arraycopy(elementData, 0, v.array_, 0, elementData.length); return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** * Returns an array containing all of the elements in this list in the * correct order. */ public Object[] toArray() { Object[] elementData = array(); Object[] result = new Object[elementData.length]; System.arraycopy(elementData, 0, result, 0, elementData.length); return result; } /** * Returns an array containing all of the elements in this list in the * correct order. The runtime type of the returned array is that of the * specified array. If the list fits in the specified array, it is returned * therein. Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this list. * <p> * If the list fits in the specified array with room to spare (i.e., the * array has more elements than the list), the element in the array * immediately following the end of the collection is set to null. This is * useful in determining the length of the list <em>only</em> if the * caller knows that the list does not contain any null elements. * * @param a * the array into which the elements of the list are to be * stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list. * @exception ArrayStoreException * the runtime type of a is not a supertype of the runtime * type of every element in this list. */ public Object[] toArray(Object a[]) { Object[] elementData = array(); if (a.length < elementData.length) a = (Object[]) java.lang.reflect.Array.newInstance(a.getClass() .getComponentType(), elementData.length); System.arraycopy(elementData, 0, a, 0, elementData.length); if (a.length > elementData.length) a[elementData.length] = null; return a; } // Positional Access Operations /** * Returns the element at the specified position in this list. * * @param index * index of element to return. * @exception IndexOutOfBoundsException * index is out of range (index &lt; 0 || index &gt;= * size()). */ public Object get(int index) { Object[] elementData = array(); rangeCheck(index, elementData.length); return elementData[index]; } /** * Replaces the element at the specified position in this list with the * specified element. * * @param index * index of element to replace. * @param element * element to be stored at the specified position. * @return the element previously at the specified position. * @exception IndexOutOfBoundsException * index out of range (index &lt; 0 || index &gt;= size()). */ public synchronized Object set(int index, Object element) { int len = array_.length; rangeCheck(index, len); Object oldValue = array_[index]; boolean same = (oldValue == element || (element != null && element .equals(oldValue))); if (!same) { Object[] newArray = new Object[len]; System.arraycopy(array_, 0, newArray, 0, len); newArray[index] = element; array_ = newArray; } return oldValue; } /** * Appends the specified element to the end of this list. * * @param element * element to be appended to this list. * @return true (as per the general contract of Collection.add). */ public synchronized boolean add(Object element) { int len = array_.length; Object[] newArray = new Object[len + 1]; System.arraycopy(array_, 0, newArray, 0, len); newArray[len] = element; array_ = newArray; return true; } /** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices). * * @param index * index at which the specified element is to be inserted. * @param element * element to be inserted. * @exception IndexOutOfBoundsException * index is out of range (index &lt; 0 || index &gt; size()). */ public synchronized void add(int index, Object element) { int len = array_.length; if (index > len || index < 0) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + len); Object[] newArray = new Object[len + 1]; System.arraycopy(array_, 0, newArray, 0, index); newArray[index] = element; System.arraycopy(array_, index, newArray, index + 1, len - index); array_ = newArray; } /** * Removes the element at the specified position in this list. Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list. * * @exception IndexOutOfBoundsException * index out of range (index &lt; 0 || index &gt;= size()). * @param index * the index of the element to removed. */ public synchronized Object remove(int index) { int len = array_.length; rangeCheck(index, len); Object oldValue = array_[index]; Object[] newArray = new Object[len - 1]; System.arraycopy(array_, 0, newArray, 0, index); int numMoved = len - index - 1; if (numMoved > 0) System.arraycopy(array_, index + 1, newArray, index, numMoved); array_ = newArray; return oldValue; } /** * Removes a single instance of the specified element from this Collection, * if it is present (optional operation). More formally, removes an element * <code>e</code> such that <code>(o==null ? e==null : * o.equals(e))</code>, * if the Collection contains one or more such elements. Returns true if the * Collection contained the specified element (or equivalently, if the * Collection changed as a result of the call). * * @param element * element to be removed from this Collection, if present. * @return true if the Collection changed as a result of the call. */ public synchronized boolean remove(Object element) { int len = array_.length; if (len == 0) return false; // Copy while searching for element to remove // This wins in the normal case of element being present int newlen = len - 1; Object[] newArray = new Object[newlen]; for (int i = 0; i < newlen; ++i) { if (element == array_[i] || (element != null && element.equals(array_[i]))) { // found one; copy remaining and exit for (int k = i + 1; k < len; ++k) newArray[k - 1] = array_[k]; array_ = newArray; return true; } else newArray[i] = array_[i]; } // special handling for last cell if (element == array_[newlen] || (element != null && element.equals(array_[newlen]))) { array_ = newArray; return true; } else return false; // throw away copy } /** * Removes from this List all of the elements whose index is between * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding * elements to the left (reduces their index). This call shortens the List * by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation * has no effect.) * * @param fromIndex * index of first element to be removed. * @param fromIndex * index after last element to be removed. * @exception IndexOutOfBoundsException * fromIndex or toIndex out of range (fromIndex &lt; 0 || * fromIndex &gt;= size() || toIndex &gt; size() || toIndex * &lt; fromIndex). */ public synchronized void removeRange(int fromIndex, int toIndex) { int len = array_.length; if (fromIndex < 0 || fromIndex >= len || toIndex > len || toIndex < fromIndex) throw new IndexOutOfBoundsException(); int numMoved = len - toIndex; int newlen = len - (toIndex - fromIndex); Object[] newArray = new Object[newlen]; System.arraycopy(array_, 0, newArray, 0, fromIndex); System.arraycopy(array_, toIndex, newArray, fromIndex, numMoved); array_ = newArray; } /** * Append the element if not present. This operation can be used to obtain * Set semantics for lists. * * @param element * element to be added to this Collection, if absent. * @return true if added */ public synchronized boolean addIfAbsent(Object element) { // Copy while checking if already present. // This wins in the most common case where it is not present int len = array_.length; Object[] newArray = new Object[len + 1]; for (int i = 0; i < len; ++i) { if (element == array_[i] || (element != null && element.equals(array_[i]))) return false; // exit, throwing away copy else newArray[i] = array_[i]; } newArray[len] = element; array_ = newArray; return true; } /** * Returns true if this Collection contains all of the elements in the * specified Collection. * <p> * This implementation iterates over the specified Collection, checking each * element returned by the Iterator in turn to see if it's contained in this * Collection. If all elements are so contained true is returned, otherwise * false. * */ public boolean containsAll(Collection c) { Object[] elementData = array(); int len = elementData.length; Iterator e = c.iterator(); while (e.hasNext()) if (indexOf(e.next(), elementData, len) < 0) return false; return true; } /** * Removes from this Collection all of its elements that are contained in * the specified Collection. This is a particularly expensive operation in * this class because of the need for an internal temporary array. * <p> * * @return true if this Collection changed as a result of the call. */ public synchronized boolean removeAll(Collection c) { Object[] elementData = array_; int len = elementData.length; if (len == 0) return false; // temp array holds those elements we know we want to keep Object[] temp = new Object[len]; int newlen = 0; for (int i = 0; i < len; ++i) { Object element = elementData[i]; if (!c.contains(element)) { temp[newlen++] = element; } } if (newlen == len) return false; // copy temp as new array Object[] newArray = new Object[newlen]; System.arraycopy(temp, 0, newArray, 0, newlen); array_ = newArray; return true; } /** * Retains only the elements in this Collection that are contained in the * specified Collection (optional operation). In other words, removes from * this Collection all of its elements that are not contained in the * specified Collection. * * @return true if this Collection changed as a result of the call. */ public synchronized boolean retainAll(Collection c) { Object[] elementData = array_; int len = elementData.length; if (len == 0) return false; Object[] temp = new Object[len]; int newlen = 0; for (int i = 0; i < len; ++i) { Object element = elementData[i]; if (c.contains(element)) { temp[newlen++] = element; } } if (newlen == len) return false; Object[] newArray = new Object[newlen]; System.arraycopy(temp, 0, newArray, 0, newlen); array_ = newArray; return true; } /** * Appends all of the elements in the specified Collection that are not * already contained in this list, to the end of this list, in the order * that they are returned by the specified Collection's Iterator. * * @param c * elements to be added into this list. * @return the number of elements added */ public synchronized int addAllAbsent(Collection c) { int numNew = c.size(); if (numNew == 0) return 0; Object[] elementData = array_; int len = elementData.length; Object[] temp = new Object[numNew]; int added = 0; Iterator e = c.iterator(); while (e.hasNext()) { Object element = e.next(); if (indexOf(element, elementData, len) < 0) { if (indexOf(element, temp, added) < 0) { temp[added++] = element; } } } if (added == 0) return 0; Object[] newArray = new Object[len + added]; System.arraycopy(elementData, 0, newArray, 0, len); System.arraycopy(temp, 0, newArray, len, added); array_ = newArray; return added; } /** * Removes all of the elements from this list. * */ public synchronized void clear() { array_ = new Object[0]; } /** * Appends all of the elements in the specified Collection to the end of * this list, in the order that they are returned by the specified * Collection's Iterator. * * @param c * elements to be inserted into this list. */ public synchronized boolean addAll(Collection c) { int numNew = c.size(); if (numNew == 0) return false; int len = array_.length; Object[] newArray = new Object[len + numNew]; System.arraycopy(array_, 0, newArray, 0, len); Iterator e = c.iterator(); for (int i = 0; i < numNew; i++) newArray[len++] = e.next(); array_ = newArray; return true; } /** * Inserts all of the elements in the specified Collection into this list, * starting at the specified position. Shifts the element currently at that * position (if any) and any subsequent elements to the right (increases * their indices). The new elements will appear in the list in the order * that they are returned by the specified Collection's iterator. * * @param index * index at which to insert first element from the specified * collection. * @param c * elements to be inserted into this list. * @exception IndexOutOfBoundsException * index out of range (index &lt; 0 || index &gt; size()). */ public synchronized boolean addAll(int index, Collection c) { int len = array_.length; if (index > len || index < 0) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + len); int numNew = c.size(); if (numNew == 0) return false; Object[] newArray = new Object[len + numNew]; System.arraycopy(array_, 0, newArray, 0, len); int numMoved = len - index; if (numMoved > 0) System.arraycopy(array_, index, newArray, index + numNew, numMoved); Iterator e = c.iterator(); for (int i = 0; i < numNew; i++) newArray[index++] = e.next(); array_ = newArray; return true; } /** * Check if the given index is in range. If not, throw an appropriate * runtime exception. */ protected void rangeCheck(int index, int length) { if (index >= length || index < 0) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + length); } /** * Save the state of the list to a stream (i.e., serialize it). * * @serialData The length of the array backing the list is emitted (int), * followed by all of its elements (each an Object) in the * proper order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out element count, and any hidden stuff s.defaultWriteObject(); Object[] elementData = array(); // Write out array length s.writeInt(elementData.length); // Write out all elements in the proper order. for (int i = 0; i < elementData.length; i++) s.writeObject(elementData[i]); } /** * Reconstitute the list from a stream (i.e., deserialize it). */ private synchronized void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in size, and any hidden stuff s.defaultReadObject(); // Read in array length and allocate array int arrayLength = s.readInt(); Object[] elementData = new Object[arrayLength]; // Read in all elements in the proper order. for (int i = 0; i < elementData.length; i++) elementData[i] = s.readObject(); array_ = elementData; } /** * Returns a string representation of this Collection, containing the String * representation of each element. */ public String toString() { StringBuffer buf = new StringBuffer(); Iterator e = iterator(); buf.append("["); int maxIndex = size() - 1; for (int i = 0; i <= maxIndex; i++) { buf.append(String.valueOf(e.next())); if (i < maxIndex) buf.append(", "); } buf.append("]"); return buf.toString(); } /** * Compares the specified Object with this List for equality. Returns true * if and only if the specified Object is also a List, both Lists have the * same size, and all corresponding pairs of elements in the two Lists are * <em>equal</em>. (Two elements <code>e1</code> and <code>e2</code> * are <em>equal</em> if * <code>(e1==null ? e2==null : e1.equals(e2))</code>.) In other words, * two Lists are defined to be equal if they contain the same elements in * the same order. * <p> * This implementation first checks if the specified object is this List. If * so, it returns true; if not, it checks if the specified object is a List. * If not, it returns false; if so, it iterates over both lists, comparing * corresponding pairs of elements. If any comparison returns false, this * method returns false. If either Iterator runs out of elements before * before the other it returns false (as the Lists are of unequal length); * otherwise it returns true when the iterations complete. * * @param o * the Object to be compared for equality with this List. * @return true if the specified Object is equal to this List. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; List l2 = (List) (o); if (size() != l2.size()) return false; ListIterator e1 = listIterator(); ListIterator e2 = l2.listIterator(); while (e1.hasNext()) { Object o1 = e1.next(); Object o2 = e2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return false; } return true; } /** * Returns the hash code value for this List. * <p> * This implementation uses exactly the code that is used to define the List * hash function in the documentation for List.hashCode. */ public int hashCode() { int hashCode = 1; Iterator i = iterator(); while (i.hasNext()) { Object obj = i.next(); hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); } return hashCode; } /** * Returns an Iterator over the elements contained in this collection. The * iterator provides a snapshot of the state of the list when the iterator * was constructed. No synchronization is needed while traversing the * iterator. The iterator does <em>NOT</em> support the * <code>remove</code> method. */ public Iterator iterator() { return new COWIterator(array(), 0); } /** * Returns an Iterator of the elements in this List (in proper sequence). * The iterator provides a snapshot of the state of the list when the * iterator was constructed. No synchronization is needed while traversing * the iterator. The iterator does <em>NOT</em> support the * <code>remove</code>,<code>set</code>, or <code>add</code> * methods. * */ public ListIterator listIterator() { return new COWIterator(array(), 0); } /** * Returns a ListIterator of 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 * nextElement. An initial call to previousElement would return the element * with the specified index minus one. The ListIterator returned by this * implementation will throw an UnsupportedOperationException in its remove, * set and add methods. * * @param index * index of first element to be returned from the ListIterator * (by a call to getNext). * @exception IndexOutOfBoundsException * index is out of range (index &lt; 0 || index &gt; size()). */ public ListIterator listIterator(final int index) { Object[] elementData = array(); int len = elementData.length; if (index < 0 || index > len) throw new IndexOutOfBoundsException("Index: " + index); return new COWIterator(array(), index); } protected static class COWIterator implements ListIterator { /** Snapshot of the array * */ protected final Object[] array; /** * Index of element to be returned by subsequent call to next. */ protected int cursor; protected COWIterator(Object[] elementArray, int initialCursor) { array = elementArray; cursor = initialCursor; } public boolean hasNext() { return cursor < array.length; } public boolean hasPrevious() { return cursor > 0; } public Object next() { try { return array[cursor++]; } catch (IndexOutOfBoundsException ex) { throw new NoSuchElementException(); } } public Object previous() { try { return array[--cursor]; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } /** * Not supported. Always throws UnsupportedOperationException. * * @exception UnsupportedOperationException * remove is not supported by this Iterator. */ public void remove() { throw new UnsupportedOperationException(); } /** * Not supported. Always throws UnsupportedOperationException. * * @exception UnsupportedOperationException * set is not supported by this Iterator. */ public void set(Object o) { throw new UnsupportedOperationException(); } /** * Not supported. Always throws UnsupportedOperationException. * * @exception UnsupportedOperationException * add is not supported by this Iterator. */ public void add(Object o) { throw new UnsupportedOperationException(); } } /** * Returns a view of the portion of this List between fromIndex, inclusive, * and toIndex, exclusive. The returned List is backed by this List, so * changes in the returned List are reflected in this List, and vice-versa. * While mutative operations are supported, they are probably not very * useful for CopyOnWriteArrays. * </p> * The semantics of the List returned by this method become undefined if the * backing list (i.e., this List) is <i>structurally modified </i> in any * way other than via the returned List. (Structural modifications are those * that change the size of the List, or otherwise perturb it in such a * fashion that iterations in progress may yield incorrect results.) * * @param fromIndex * low endpoint (inclusive) of the subList. * @param toKey * high endpoint (exclusive) of the subList. * @return a view of the specified range within this List. * @exception IndexOutOfBoundsException * Illegal endpoint index value (fromIndex &lt; 0 || toIndex * &gt; size || fromIndex &gt; toIndex). */ public synchronized List subList(int fromIndex, int toIndex) { // synchronized since sublist ctor depends on it. int len = array_.length; if (fromIndex < 0 || toIndex > len || fromIndex > toIndex) throw new IndexOutOfBoundsException(); return new COWSubList(this, fromIndex, toIndex); } protected static class COWSubList extends AbstractList { /* * This is currently a bit sleazy. The class extends AbstractList merely * for convenience, to avoid having to define addAll, etc. This doesn't * hurt, but is stupid and wasteful. This class does not need or use * modCount mechanics in AbstractList, but does need to check for * concurrent modification using similar mechanics. On each operation, * the array that we expect the backing list to use is checked and * updated. Since we do this for all of the base operations invoked by * those defined in AbstractList, all is well. * * It's not clear whether this is worth cleaning up. The kinds of list * operations inherited from AbstractList are are already so slow on COW * sublists that adding a bit more space/time doesn't seem even * noticeable. */ protected final CopyOnWriteArrayList l; protected final int offset; protected int size; protected Object[] expectedArray; protected COWSubList(CopyOnWriteArrayList list, int fromIndex, int toIndex) { l = list; expectedArray = l.array(); offset = fromIndex; size = toIndex - fromIndex; } // only call this holding l's lock protected void checkForComodification() { if (l.array_ != expectedArray) throw new ConcurrentModificationException(); } // only call this holding l's lock protected void rangeCheck(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ",Size: " + size); } public Object set(int index, Object element) { synchronized (l) { rangeCheck(index); checkForComodification(); Object x = l.set(index + offset, element); expectedArray = l.array_; return x; } } public Object get(int index) { synchronized (l) { rangeCheck(index); checkForComodification(); return l.get(index + offset); } } public int size() { synchronized (l) { checkForComodification(); return size; } } public void add(int index, Object element) { synchronized (l) { checkForComodification(); if (index < 0 || index > size) throw new IndexOutOfBoundsException(); l.add(index + offset, element); expectedArray = l.array_; size++; } } public Object remove(int index) { synchronized (l) { rangeCheck(index); checkForComodification(); Object result = l.remove(index + offset); expectedArray = l.array_; size--; return result; } } public Iterator iterator() { synchronized (l) { checkForComodification(); return new COWSubListIterator(0); } } public ListIterator listIterator(final int index) { synchronized (l) { checkForComodification(); if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); return new COWSubListIterator(index); } } protected class COWSubListIterator implements ListIterator { protected final ListIterator i; protected final int index; protected COWSubListIterator(int index) { this.index = index; i = l.listIterator(index + offset); } public boolean hasNext() { return nextIndex() < size; } public Object next() { if (hasNext()) return i.next(); else throw new NoSuchElementException(); } public boolean hasPrevious() { return previousIndex() >= 0; } public Object previous() { if (hasPrevious()) return i.previous(); else throw new NoSuchElementException(); } public int nextIndex() { return i.nextIndex() - offset; } public int previousIndex() { return i.previousIndex() - offset; } public void remove() { throw new UnsupportedOperationException(); } public void set(Object o) { throw new UnsupportedOperationException(); } public void add(Object o) { throw new UnsupportedOperationException(); } } public List subList(int fromIndex, int toIndex) { synchronized (l) { checkForComodification(); if (fromIndex < 0 || toIndex > size) throw new IndexOutOfBoundsException(); return new COWSubList(l, fromIndex + offset, toIndex + offset); } } } }

The table below shows all metrics for CopyOnWriteArrayList.java.

MetricValueDescription
BLOCKS110.00Number of blocks
BLOCK_COMMENT38.00Number of block comment lines
COMMENTS509.00Comment lines
COMMENT_DENSITY 1.05Comment density
COMPARISONS108.00Number of comparison operators
CYCLOMATIC174.00Cyclomatic complexity
DECL_COMMENTS55.00Comments in declarations
DOC_COMMENT450.00Number of javadoc comment lines
ELOC485.00Effective lines of code
EXEC_COMMENTS15.00Comments in executable code
EXITS46.00Procedure exits
FUNCTIONS73.00Number of function declarations
HALSTEAD_DIFFICULTY116.87Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY188.00Interface complexity
JAVA0001 1.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003446.00JAVA0034 Missing braces in if statement
JAVA003513.00JAVA0035 Missing braces in for statement
JAVA0036 2.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 1.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 9.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 2.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA011014.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 1.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 3.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 6.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 1.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA014317.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA01452170.00JAVA0145 Tab character used in source file
JAVA0150 1.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 0.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 5.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 2.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 1.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 1.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 1.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 4.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1352.00Number of lines in the source file
LINE_COMMENT21.00Number of line comments
LOC712.00Lines of code
LOGICAL_LINES327.00Number of statements
LOOPS23.00Number of loops
NEST_DEPTH 4.00Maximum nesting depth
OPERANDS1338.00Number of operands
OPERATORS2612.00Number of operators
PARAMS65.00Number of formal parameter declarations
PROGRAM_LENGTH3950.00Halstead program length
PROGRAM_VOCAB390.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS123.00Number of return points from functions
SIZE37352.00Size of the file in bytes
UNIQUE_OPERANDS332.00Number of unique operands
UNIQUE_OPERATORS58.00Number of unique operators
WHITESPACE131.00Number of whitespace lines