SequencedHashMap.java

Index Score
org.apache.commons.collections
Commons Collections

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
LINE_COMMENTNumber of line comments
DECL_COMMENTSComments in declarations
EXEC_COMMENTSComments in executable code
COMMENTSComment lines
DOC_COMMENTNumber of javadoc comment lines
JAVA0034JAVA0034 Missing braces in if statement
RETURNSNumber of return points from functions
SIZESize of the file in bytes
FUNCTIONSNumber of function declarations
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
INTERFACE_COMPLEXITYInterface complexity
LINESNumber of lines in the source file
CYCLOMATICCyclomatic complexity
LOOPSNumber of loops
BLOCKSNumber of blocks
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
LOGICAL_LINESNumber of statements
OPERATORSNumber of operators
COMPARISONSNumber of comparison operators
LOCLines of code
ELOCEffective lines of code
PROGRAM_LENGTHHalstead program length
JAVA0128JAVA0128 Public constructor in non-public class
JAVA0242JAVA0242 Transient field in non-Serializable class
OPERANDSNumber of operands
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
PARAMSNumber of formal parameter declarations
PROGRAM_VOCABHalstead program vocabulary
JAVA0150JAVA0150 java.lang.Error (or subclass) thrown
UNIQUE_OPERANDSNumber of unique operands
UNIQUE_OPERATORSNumber of unique operators
JAVA0064JAVA0064 N variations of identifier name (maximum: M)
EXITSProcedure exits
JAVA0084JAVA0084 Should use compound assignment operator
JAVA0077JAVA0077 Private field not used in declaring class
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0132JAVA0132 Method overload with compatible signature
JAVA0117JAVA0117 Missing javadoc: method 'method'
WHITESPACENumber of whitespace lines
JAVA0130JAVA0130 Non-static method does not use instance fields
NEST_DEPTHMaximum nesting depth
JAVA0145JAVA0145 Tab character used in source file
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.list.UnmodifiableList; /** * A map of objects whose mapping entries are sequenced based on the order in * which they were added. This data structure has fast <i>O(1)</i> search * time, deletion time, and insertion time. * <p> * Although this map is sequenced, it cannot implement * {@link java.util.List} because of incompatible interface definitions. * The remove methods in List and Map have different return values * (see: {@link java.util.List#remove(Object)} and {@link java.util.Map#remove(Object)}). * <p> * This class is not thread safe. When a thread safe implementation is * required, use {@link java.util.Collections#synchronizedMap(Map)} as it is documented, * or use explicit synchronization controls. * * @deprecated Replaced by LinkedMap and ListOrderedMap in map subpackage. Due to be removed in v4.0. * @see org.apache.commons.collections.map.LinkedMap * @see org.apache.commons.collections.map.ListOrderedMap * @since Commons Collections 2.0 * @version $Revision: 480452 $ $Date: 2006-11-29 02:45:14 -0500 (Wed, 29 Nov 2006) $ * * @author Michael A. Smith * @author Daniel Rall * @author Henning P. Schmiedehausen * @author Stephen Colebourne */ public class SequencedHashMap implements Map, Cloneable, Externalizable { /** * {@link java.util.Map.Entry} that doubles as a node in the linked list * of sequenced mappings. */ private static class Entry implements Map.Entry, KeyValue { // Note: This class cannot easily be made clonable. While the actual // implementation of a clone would be simple, defining the semantics is // difficult. If a shallow clone is implemented, then entry.next.prev != // entry, which is unintuitive and probably breaks all sorts of assumptions // in code that uses this implementation. If a deep clone is // implemented, then what happens when the linked list is cyclical (as is // the case with SequencedHashMap)? It's impossible to know in the clone // when to stop cloning, and thus you end up in a recursive loop, // continuously cloning the "next" in the list. private final Object key; private Object value; // package private to allow the SequencedHashMap to access and manipulate // them. Entry next = null; Entry prev = null; public Entry(Object key, Object value) { this.key = key; this.value = value; } // per Map.Entry.getKey() public Object getKey() { return this.key; } // per Map.Entry.getValue() public Object getValue() { return this.value; } // per Map.Entry.setValue() public Object setValue(Object value) { Object oldValue = this.value; this.value = value; return oldValue; } public int hashCode() { // implemented per api docs for Map.Entry.hashCode() return ((getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode())); } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Map.Entry)) return false; Map.Entry other = (Map.Entry) obj; // implemented per api docs for Map.Entry.equals(Object) return ( (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()))); } public String toString() { return "[" + getKey() + "=" + getValue() + "]"; } } /** * Construct an empty sentinel used to hold the head (sentinel.next) and the * tail (sentinel.prev) of the list. The sentinel has a <code>null</code> * key and value. */ private static final Entry createSentinel() { Entry s = new Entry(null, null); s.prev = s; s.next = s; return s; } /** * Sentinel used to hold the head and tail of the list of entries. */ private Entry sentinel; /** * Map of keys to entries */ private HashMap entries; /** * Holds the number of modifications that have occurred to the map, * excluding modifications made through a collection view's iterator * (e.g. entrySet().iterator().remove()). This is used to create a * fail-fast behavior with the iterators. */ private transient long modCount = 0; /** * Construct a new sequenced hash map with default initial size and load * factor. */ public SequencedHashMap() { sentinel = createSentinel(); entries = new HashMap(); } /** * Construct a new sequenced hash map with the specified initial size and * default load factor. * * @param initialSize the initial size for the hash table * * @see HashMap#HashMap(int) */ public SequencedHashMap(int initialSize) { sentinel = createSentinel(); entries = new HashMap(initialSize); } /** * Construct a new sequenced hash map with the specified initial size and * load factor. * * @param initialSize the initial size for the hash table * * @param loadFactor the load factor for the hash table. * * @see HashMap#HashMap(int,float) */ public SequencedHashMap(int initialSize, float loadFactor) { sentinel = createSentinel(); entries = new HashMap(initialSize, loadFactor); } /** * Construct a new sequenced hash map and add all the elements in the * specified map. The order in which the mappings in the specified map are * added is defined by {@link #putAll(Map)}. */ public SequencedHashMap(Map m) { this(); putAll(m); } /** * Removes an internal entry from the linked list. This does not remove * it from the underlying map. */ private void removeEntry(Entry entry) { entry.next.prev = entry.prev; entry.prev.next = entry.next; } /** * Inserts a new internal entry to the tail of the linked list. This does * not add the entry to the underlying map. */ private void insertEntry(Entry entry) { entry.next = sentinel; entry.prev = sentinel.prev; sentinel.prev.next = entry; sentinel.prev = entry; } // per Map.size() /** * Implements {@link Map#size()}. */ public int size() { // use the underlying Map's size since size is not maintained here. return entries.size(); } /** * Implements {@link Map#isEmpty()}. */ public boolean isEmpty() { // for quick check whether the map is entry, we can check the linked list // and see if there's anything in it. return sentinel.next == sentinel; } /** * Implements {@link Map#containsKey(Object)}. */ public boolean containsKey(Object key) { // pass on to underlying map implementation return entries.containsKey(key); } /** * Implements {@link Map#containsValue(Object)}. */ public boolean containsValue(Object value) { // unfortunately, we cannot just pass this call to the underlying map // because we are mapping keys to entries, not keys to values. The // underlying map doesn't have an efficient implementation anyway, so this // isn't a big deal. // do null comparison outside loop so we only need to do it once. This // provides a tighter, more efficient loop at the expense of slight // code duplication. if (value == null) { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (pos.getValue() == null) return true; } } else { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (value.equals(pos.getValue())) return true; } } return false; } /** * Implements {@link Map#get(Object)}. */ public Object get(Object o) { // find entry for the specified key object Entry entry = (Entry) entries.get(o); if (entry == null) return null; return entry.getValue(); } /** * Return the entry for the "oldest" mapping. That is, return the Map.Entry * for the key-value pair that was first put into the map when compared to * all the other pairings in the map. This behavior is equivalent to using * <code>entrySet().iterator().next()</code>, but this method provides an * optimized implementation. * * @return The first entry in the sequence, or <code>null</code> if the * map is empty. */ public Map.Entry getFirst() { // sentinel.next points to the "first" element of the sequence -- the head // of the list, which is exactly the entry we need to return. We must test // for an empty list though because we don't want to return the sentinel! return (isEmpty()) ? null : sentinel.next; } /** * Return the key for the "oldest" mapping. That is, return the key for the * mapping that was first put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * <code>getFirst().getKey()</code>, but this method provides a slightly * optimized implementation. * * @return The first key in the sequence, or <code>null</code> if the * map is empty. */ public Object getFirstKey() { // sentinel.next points to the "first" element of the sequence -- the head // of the list -- and the requisite key is returned from it. An empty list // does not need to be tested. In cases where the list is empty, // sentinel.next will point to the sentinel itself which has a null key, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.next.getKey(); } /** * Return the value for the "oldest" mapping. That is, return the value for * the mapping that was first put into the map when compared to all the * other objects in the map. This behavior is equivalent to using * <code>getFirst().getValue()</code>, but this method provides a slightly * optimized implementation. * * @return The first value in the sequence, or <code>null</code> if the * map is empty. */ public Object getFirstValue() { // sentinel.next points to the "first" element of the sequence -- the head // of the list -- and the requisite value is returned from it. An empty // list does not need to be tested. In cases where the list is empty, // sentinel.next will point to the sentinel itself which has a null value, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.next.getValue(); } /** * Return the entry for the "newest" mapping. That is, return the Map.Entry * for the key-value pair that was first put into the map when compared to * all the other pairings in the map. The behavior is equivalent to: * * <pre> * Object obj = null; * Iterator iter = entrySet().iterator(); * while(iter.hasNext()) { * obj = iter.next(); * } * return (Map.Entry)obj; * </pre> * * However, the implementation of this method ensures an O(1) lookup of the * last key rather than O(n). * * @return The last entry in the sequence, or <code>null</code> if the map * is empty. */ public Map.Entry getLast() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list, which is exactly the entry we need to return. We must test // for an empty list though because we don't want to return the sentinel! return (isEmpty()) ? null : sentinel.prev; } /** * Return the key for the "newest" mapping. That is, return the key for the * mapping that was last put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * <code>getLast().getKey()</code>, but this method provides a slightly * optimized implementation. * * @return The last key in the sequence, or <code>null</code> if the map is * empty. */ public Object getLastKey() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list -- and the requisite key is returned from it. An empty list // does not need to be tested. In cases where the list is empty, // sentinel.prev will point to the sentinel itself which has a null key, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.prev.getKey(); } /** * Return the value for the "newest" mapping. That is, return the value for * the mapping that was last put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * <code>getLast().getValue()</code>, but this method provides a slightly * optimized implementation. * * @return The last value in the sequence, or <code>null</code> if the map * is empty. */ public Object getLastValue() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list -- and the requisite value is returned from it. An empty // list does not need to be tested. In cases where the list is empty, // sentinel.prev will point to the sentinel itself which has a null value, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.prev.getValue(); } /** * Implements {@link Map#put(Object, Object)}. */ public Object put(Object key, Object value) { modCount++; Object oldValue = null; // lookup the entry for the specified key Entry e = (Entry) entries.get(key); // check to see if it already exists if (e != null) { // remove from list so the entry gets "moved" to the end of list removeEntry(e); // update value in map oldValue = e.setValue(value); // Note: We do not update the key here because its unnecessary. We only // do comparisons using equals(Object) and we know the specified key and // that in the map are equal in that sense. This may cause a problem if // someone does not implement their hashCode() and/or equals(Object) // method properly and then use it as a key in this map. } else { // add new entry e = new Entry(key, value); entries.put(key, e); } // assert(entry in map, but not list) // add to list insertEntry(e); return oldValue; } /** * Implements {@link Map#remove(Object)}. */ public Object remove(Object key) { Entry e = removeImpl(key); return (e == null) ? null : e.getValue(); } /** * Fully remove an entry from the map, returning the old entry or null if * there was no such entry with the specified key. */ private Entry removeImpl(Object key) { Entry e = (Entry) entries.remove(key); if (e == null) return null; modCount++; removeEntry(e); return e; } /** * Adds all the mappings in the specified map to this map, replacing any * mappings that already exist (as per {@link Map#putAll(Map)}). The order * in which the entries are added is determined by the iterator returned * from {@link Map#entrySet()} for the specified map. * * @param t the mappings that should be added to this map. * * @throws NullPointerException if <code>t</code> is <code>null</code> */ public void putAll(Map t) { Iterator iter = t.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); put(entry.getKey(), entry.getValue()); } } /** * Implements {@link Map#clear()}. */ public void clear() { modCount++; // remove all from the underlying map entries.clear(); // and the list sentinel.next = sentinel; sentinel.prev = sentinel; } /** * Implements {@link Map#equals(Object)}. */ public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Map)) return false; return entrySet().equals(((Map) obj).entrySet()); } /** * Implements {@link Map#hashCode()}. */ public int hashCode() { return entrySet().hashCode(); } /** * Provides a string representation of the entries within the map. The * format of the returned string may change with different releases, so this * method is suitable for debugging purposes only. If a specific format is * required, use {@link #entrySet()}.{@link Set#iterator() iterator()} and * iterate over the entries in the map formatting them as appropriate. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append('['); for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { buf.append(pos.getKey()); buf.append('='); buf.append(pos.getValue()); if (pos.next != sentinel) { buf.append(','); } } buf.append(']'); return buf.toString(); } /** * Implements {@link Map#keySet()}. */ public Set keySet() { return new AbstractSet() { // required impls public Iterator iterator() { return new OrderedIterator(KEY); } public boolean remove(Object o) { Entry e = SequencedHashMap.this.removeImpl(o); return (e != null); } // more efficient impls than abstract set public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return SequencedHashMap.this.containsKey(o); } }; } /** * Implements {@link Map#values()}. */ public Collection values() { return new AbstractCollection() { // required impl public Iterator iterator() { return new OrderedIterator(VALUE); } public boolean remove(Object value) { // do null comparison outside loop so we only need to do it once. This // provides a tighter, more efficient loop at the expense of slight // code duplication. if (value == null) { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (pos.getValue() == null) { SequencedHashMap.this.removeImpl(pos.getKey()); return true; } } } else { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (value.equals(pos.getValue())) { SequencedHashMap.this.removeImpl(pos.getKey()); return true; } } } return false; } // more efficient impls than abstract collection public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return SequencedHashMap.this.containsValue(o); } }; } /** * Implements {@link Map#entrySet()}. */ public Set entrySet() { return new AbstractSet() { // helper private Entry findEntry(Object o) { if (o == null) return null; if (!(o instanceof Map.Entry)) return null; Map.Entry e = (Map.Entry) o; Entry entry = (Entry) entries.get(e.getKey()); if (entry != null && entry.equals(e)) return entry; else return null; } // required impl public Iterator iterator() { return new OrderedIterator(ENTRY); } public boolean remove(Object o) { Entry e = findEntry(o); if (e == null) return false; return SequencedHashMap.this.removeImpl(e.getKey()) != null; } // more efficient impls than abstract collection public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return findEntry(o) != null; } }; } // constants to define what the iterator should return on "next" private static final int KEY = 0; private static final int VALUE = 1; private static final int ENTRY = 2; private static final int REMOVED_MASK = 0x80000000; private class OrderedIterator implements Iterator { /** * Holds the type that should be returned from the iterator. The value * should be either {@link #KEY}, {@link #VALUE}, or {@link #ENTRY}. To * save a tiny bit of memory, this field is also used as a marker for when * remove has been called on the current object to prevent a second remove * on the same element. Essentially, if this value is negative (i.e. the * bit specified by {@link #REMOVED_MASK} is set), the current position * has been removed. If positive, remove can still be called. */ private int returnType; /** * Holds the "current" position in the iterator. When pos.next is the * sentinel, we've reached the end of the list. */ private Entry pos = sentinel; /** * Holds the expected modification count. If the actual modification * count of the map differs from this value, then a concurrent * modification has occurred. */ private transient long expectedModCount = modCount; /** * Construct an iterator over the sequenced elements in the order in which * they were added. The {@link #next()} method returns the type specified * by <code>returnType</code> which must be either {@link #KEY}, {@link * #VALUE}, or {@link #ENTRY}. */ public OrderedIterator(int returnType) { //// Since this is a private inner class, nothing else should have //// access to the constructor. Since we know the rest of the outer //// class uses the iterator correctly, we can leave of the following //// check: //if(returnType >= 0 && returnType <= 2) { // throw new IllegalArgumentException("Invalid iterator type"); //} // Set the "removed" bit so that the iterator starts in a state where // "next" must be called before "remove" will succeed. this.returnType = returnType | REMOVED_MASK; } /** * Returns whether there is any additional elements in the iterator to be * returned. * * @return <code>true</code> if there are more elements left to be * returned from the iterator; <code>false</code> otherwise. */ public boolean hasNext() { return pos.next != sentinel; } /** * Returns the next element from the iterator. * * @return the next element from the iterator. * * @throws NoSuchElementException if there are no more elements in the * iterator. * * @throws ConcurrentModificationException if a modification occurs in * the underlying map. */ public Object next() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (pos.next == sentinel) { throw new NoSuchElementException(); } // clear the "removed" flag returnType = returnType & ~REMOVED_MASK; pos = pos.next; switch (returnType) { case KEY : return pos.getKey(); case VALUE : return pos.getValue(); case ENTRY : return pos; default : // should never happen throw new Error("bad iterator type: " + returnType); } } /** * Removes the last element returned from the {@link #next()} method from * the sequenced map. * * @throws IllegalStateException if there isn't a "last element" to be * removed. That is, if {@link #next()} has never been called, or if * {@link #remove()} was already called on the element. * * @throws ConcurrentModificationException if a modification occurs in * the underlying map. */ public void remove() { if ((returnType & REMOVED_MASK) != 0) { throw new IllegalStateException("remove() must follow next()"); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } SequencedHashMap.this.removeImpl(pos.getKey()); // update the expected mod count for the remove operation expectedModCount++; // set the removed flag returnType = returnType | REMOVED_MASK; } } // APIs maintained from previous version of SequencedHashMap for backwards // compatibility /** * Creates a shallow copy of this object, preserving the internal structure * by copying only references. The keys and values themselves are not * <code>clone()</code>'d. The cloned object maintains the same sequence. * * @return A clone of this instance. * * @throws CloneNotSupportedException if clone is not supported by a * subclass. */ public Object clone() throws CloneNotSupportedException { // yes, calling super.clone() silly since we're just blowing away all // the stuff that super might be doing anyway, but for motivations on // this, see: // http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html SequencedHashMap map = (SequencedHashMap) super.clone(); // create new, empty sentinel map.sentinel = createSentinel(); // create a new, empty entry map // note: this does not preserve the initial capacity and load factor. map.entries = new HashMap(); // add all the mappings map.putAll(this); // Note: We cannot just clone the hashmap and sentinel because we must // duplicate our internal structures. Cloning those two will not clone all // the other entries they reference, and so the cloned hash map will not be // able to maintain internal consistency because there are two objects with // the same entries. See discussion in the Entry implementation on why we // cannot implement a clone of the Entry (and thus why we need to recreate // everything). return map; } /** * Returns the Map.Entry at the specified index * * @throws ArrayIndexOutOfBoundsException if the specified index is * <code>&lt; 0</code> or <code>&gt;</code> the size of the map. */ private Map.Entry getEntry(int index) { Entry pos = sentinel; if (index < 0) { throw new ArrayIndexOutOfBoundsException(index + " < 0"); } // loop to one before the position int i = -1; while (i < (index - 1) && pos.next != sentinel) { i++; pos = pos.next; } // pos.next is the requested position // if sentinel is next, past end of list if (pos.next == sentinel) { throw new ArrayIndexOutOfBoundsException(index + " >= " + (i + 1)); } return pos.next; } /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index, or null * @throws ArrayIndexOutOfBoundsException if the <code>index</code> is * <code>&lt; 0</code> or <code>&gt;</code> the size of the map. */ public Object get(int index) { return getEntry(index).getKey(); } /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value at the specified index, or null * @throws ArrayIndexOutOfBoundsException if the <code>index</code> is * <code>&lt; 0</code> or <code>&gt;</code> the size of the map. */ public Object getValue(int index) { return getEntry(index).getValue(); } /** * Gets the index of the specified key. * * @param key the key to find the index of * @return the index, or -1 if not found */ public int indexOf(Object key) { Entry e = (Entry) entries.get(key); if (e == null) { return -1; } int pos = 0; while (e.prev != sentinel) { pos++; e = e.prev; } return pos; } /** * Gets an iterator over the keys. * * @return an iterator over the keys */ public Iterator iterator() { return keySet().iterator(); } /** * Gets the last index of the specified key. * * @param key the key to find the index of * @return the index, or -1 if not found */ public int lastIndexOf(Object key) { // keys in a map are guaranteed to be unique return indexOf(key); } /** * Returns a List view of the keys rather than a set view. The returned * list is unmodifiable. This is required because changes to the values of * the list (using {@link java.util.ListIterator#set(Object)}) will * effectively remove the value from the list and reinsert that value at * the end of the list, which is an unexpected side effect of changing the * value of a list. This occurs because changing the key, changes when the * mapping is added to the map and thus where it appears in the list. * * <p>An alternative to this method is to use {@link #keySet()} * * @see #keySet() * @return The ordered list of keys. */ public List sequence() { List l = new ArrayList(size()); Iterator iter = keySet().iterator(); while (iter.hasNext()) { l.add(iter.next()); } return UnmodifiableList.decorate(l); } /** * Removes the element at the specified index. * * @param index The index of the object to remove. * @return The previous value corresponding the <code>key</code>, or * <code>null</code> if none existed. * * @throws ArrayIndexOutOfBoundsException if the <code>index</code> is * <code>&lt; 0</code> or <code>&gt;</code> the size of the map. */ public Object remove(int index) { return remove(get(index)); } // per Externalizable.readExternal(ObjectInput) /** * Deserializes this map from the given stream. * * @param in the stream to deserialize from * @throws IOException if the stream raises it * @throws ClassNotFoundException if the stream raises it */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int size = in.readInt(); for (int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); put(key, value); } } /** * Serializes this map to the given stream. * * @param out the stream to serialize to * @throws IOException if the stream raises it */ public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(size()); for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { out.writeObject(pos.getKey()); out.writeObject(pos.getValue()); } } // add a serial version uid, so that if we change things in the future // without changing the format, we can still deserialize properly. private static final long serialVersionUID = 3380552487888102930L; }

The table below shows all metrics for SequencedHashMap.java.

MetricValueDescription
BLOCKS97.00Number of blocks
BLOCK_COMMENT16.00Number of block comment lines
COMMENTS487.00Comment lines
COMMENT_DENSITY 1.51Comment density
COMPARISONS58.00Number of comparison operators
CYCLOMATIC122.00Cyclomatic complexity
DECL_COMMENTS70.00Comments in declarations
DOC_COMMENT350.00Number of javadoc comment lines
ELOC323.00Effective lines of code
EXEC_COMMENTS40.00Comments in executable code
EXITS47.00Procedure exits
FUNCTIONS70.00Number of function declarations
HALSTEAD_DIFFICULTY92.69Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY139.00Interface complexity
JAVA0001 0.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
JAVA003415.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.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 3.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 1.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 2.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 0.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 6.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA011016.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 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 0.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 1.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 2.00JAVA0128 Public constructor in non-public class
JAVA0130 1.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 2.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
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.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 1.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 2.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 1.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.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 0.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 0.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 0.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
LINES1018.00Number of lines in the source file
LINE_COMMENT121.00Number of line comments
LOC421.00Lines of code
LOGICAL_LINES212.00Number of statements
LOOPS11.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS829.00Number of operands
OPERATORS1790.00Number of operators
PARAMS35.00Number of formal parameter declarations
PROGRAM_LENGTH2619.00Halstead program length
PROGRAM_VOCAB290.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS104.00Number of return points from functions
SIZE36041.00Size of the file in bytes
UNIQUE_OPERANDS237.00Number of unique operands
UNIQUE_OPERATORS53.00Number of unique operators
WHITESPACE110.00Number of whitespace lines