LinkedMap.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.collections4.map;

  18. import java.io.IOException;
  19. import java.io.ObjectInputStream;
  20. import java.io.ObjectOutputStream;
  21. import java.io.Serializable;
  22. import java.util.AbstractList;
  23. import java.util.Collection;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.ListIterator;
  27. import java.util.Map;
  28. import java.util.function.Predicate;

  29. import org.apache.commons.collections4.CollectionUtils;
  30. import org.apache.commons.collections4.iterators.UnmodifiableIterator;
  31. import org.apache.commons.collections4.iterators.UnmodifiableListIterator;
  32. import org.apache.commons.collections4.list.UnmodifiableList;

  33. /**
  34.  * A {@code Map} implementation that maintains the order of the entries.
  35.  * In this implementation order is maintained by original insertion.
  36.  * <p>
  37.  * This implementation improves on the JDK1.4 LinkedHashMap by adding the
  38.  * {@link org.apache.commons.collections4.MapIterator MapIterator}
  39.  * functionality, additional convenience methods and allowing
  40.  * bidirectional iteration. It also implements {@code OrderedMap}.
  41.  * In addition, non-interface methods are provided to access the map by index.
  42.  * </p>
  43.  * <p>
  44.  * The {@code orderedMapIterator()} method provides direct access to a
  45.  * bidirectional iterator. The iterators from the other views can also be cast
  46.  * to {@code OrderedIterator} if required.
  47.  * </p>
  48.  * <p>
  49.  * All the available iterators can be reset back to the start by casting to
  50.  * {@code ResettableIterator} and calling {@code reset()}.
  51.  * </p>
  52.  * <p>
  53.  * The implementation is also designed to be subclassed, with lots of useful
  54.  * methods exposed.
  55.  * </p>
  56.  * <p>
  57.  * <strong>Note that LinkedMap is not synchronized and is not thread-safe.</strong>
  58.  * If you wish to use this map from multiple threads concurrently, you must use
  59.  * appropriate synchronization. The simplest approach is to wrap this map
  60.  * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
  61.  * exceptions when accessed by concurrent threads without synchronization.
  62.  * </p>
  63.  *
  64.  * @param <K> the type of the keys in this map
  65.  * @param <V> the type of the values in this map
  66.  * @since 3.0
  67.  */
  68. public class LinkedMap<K, V> extends AbstractLinkedMap<K, V> implements Serializable, Cloneable {

  69.     /**
  70.      * List view of map.
  71.      */
  72.     static class LinkedMapList<K> extends AbstractList<K> {

  73.         private final LinkedMap<K, ?> parent;

  74.         LinkedMapList(final LinkedMap<K, ?> parent) {
  75.             this.parent = parent;
  76.         }

  77.         @Override
  78.         public void clear() {
  79.             throw new UnsupportedOperationException();
  80.         }

  81.         @Override
  82.         public boolean contains(final Object obj) {
  83.             return parent.containsKey(obj);
  84.         }

  85.         @Override
  86.         public boolean containsAll(final Collection<?> coll) {
  87.             return parent.keySet().containsAll(coll);
  88.         }

  89.         @Override
  90.         public K get(final int index) {
  91.             return parent.get(index);
  92.         }

  93.         @Override
  94.         public int indexOf(final Object obj) {
  95.             return parent.indexOf(obj);
  96.         }

  97.         @Override
  98.         public Iterator<K> iterator() {
  99.             return UnmodifiableIterator.unmodifiableIterator(parent.keySet().iterator());
  100.         }

  101.         @Override
  102.         public int lastIndexOf(final Object obj) {
  103.             return parent.indexOf(obj);
  104.         }

  105.         @Override
  106.         public ListIterator<K> listIterator() {
  107.             return UnmodifiableListIterator.unmodifiableListIterator(super.listIterator());
  108.         }

  109.         @Override
  110.         public ListIterator<K> listIterator(final int fromIndex) {
  111.             return UnmodifiableListIterator.unmodifiableListIterator(super.listIterator(fromIndex));
  112.         }

  113.         @Override
  114.         public K remove(final int index) {
  115.             throw new UnsupportedOperationException();
  116.         }

  117.         @Override
  118.         public boolean remove(final Object obj) {
  119.             throw new UnsupportedOperationException();
  120.         }

  121.         @Override
  122.         public boolean removeAll(final Collection<?> coll) {
  123.             throw new UnsupportedOperationException();
  124.         }

  125.         /**
  126.          * @since 4.4
  127.          */
  128.         @Override
  129.         public boolean removeIf(final Predicate<? super K> filter) {
  130.             throw new UnsupportedOperationException();
  131.         }

  132.         @Override
  133.         public boolean retainAll(final Collection<?> coll) {
  134.             throw new UnsupportedOperationException();
  135.         }

  136.         @Override
  137.         public int size() {
  138.             return parent.size();
  139.         }

  140.         @Override
  141.         public List<K> subList(final int fromIndexInclusive, final int toIndexExclusive) {
  142.             return UnmodifiableList.unmodifiableList(super.subList(fromIndexInclusive, toIndexExclusive));
  143.         }

  144.         @Override
  145.         public Object[] toArray() {
  146.             return parent.keySet().toArray();
  147.         }

  148.         @Override
  149.         public <T> T[] toArray(final T[] array) {
  150.             return parent.keySet().toArray(array);
  151.         }
  152.     }

  153.     /** Serialization version */
  154.     private static final long serialVersionUID = 9077234323521161066L;

  155.     /**
  156.      * Constructs a new empty map with default size and load factor.
  157.      */
  158.     public LinkedMap() {
  159.         super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD);
  160.     }

  161.     /**
  162.      * Constructs a new, empty map with the specified initial capacity.
  163.      *
  164.      * @param initialCapacity  the initial capacity
  165.      * @throws IllegalArgumentException if the initial capacity is negative
  166.      */
  167.     public LinkedMap(final int initialCapacity) {
  168.         super(initialCapacity);
  169.     }

  170.     /**
  171.      * Constructs a new, empty map with the specified initial capacity and
  172.      * load factor.
  173.      *
  174.      * @param initialCapacity  the initial capacity
  175.      * @param loadFactor  the load factor
  176.      * @throws IllegalArgumentException if the initial capacity is negative
  177.      * @throws IllegalArgumentException if the load factor is less than zero
  178.      */
  179.     public LinkedMap(final int initialCapacity, final float loadFactor) {
  180.         super(initialCapacity, loadFactor);
  181.     }

  182.     /**
  183.      * Constructor copying elements from another map.
  184.      *
  185.      * @param map  the map to copy
  186.      * @throws NullPointerException if the map is null
  187.      */
  188.     public LinkedMap(final Map<? extends K, ? extends V> map) {
  189.         super(map);
  190.     }

  191.     /**
  192.      * Gets an unmodifiable List view of the keys.
  193.      * <p>
  194.      * The returned list is unmodifiable because changes to the values of
  195.      * the list (using {@link java.util.ListIterator#set(Object)}) will
  196.      * effectively remove the value from the list and reinsert that value at
  197.      * the end of the list, which is an unexpected side effect of changing the
  198.      * value of a list.  This occurs because changing the key, changes when the
  199.      * mapping is added to the map and thus where it appears in the list.
  200.      * </p>
  201.      * <p>
  202.      * An alternative to this method is to use {@link #keySet()}.
  203.      * </p>
  204.      *
  205.      * @see #keySet()
  206.      * @return The ordered list of keys.
  207.      */
  208.     public List<K> asList() {
  209.         return new LinkedMapList<>(this);
  210.     }

  211.     /**
  212.      * Clones the map without cloning the keys or values.
  213.      *
  214.      * @return a shallow clone
  215.      */
  216.     @Override
  217.     public LinkedMap<K, V> clone() {
  218.         return (LinkedMap<K, V>) super.clone();
  219.     }

  220.     /**
  221.      * Gets the key at the specified index.
  222.      *
  223.      * @param index  the index to retrieve
  224.      * @return the key at the specified index
  225.      * @throws IndexOutOfBoundsException if the index is invalid
  226.      */
  227.     public K get(final int index) {
  228.         return getEntry(index).getKey();
  229.     }

  230.     /**
  231.      * Gets the value at the specified index.
  232.      *
  233.      * @param index  the index to retrieve
  234.      * @return the value at the specified index
  235.      * @throws IndexOutOfBoundsException if the index is invalid
  236.      */
  237.     public V getValue(final int index) {
  238.         return getEntry(index).getValue();
  239.     }

  240.     /**
  241.      * Gets the index of the specified key.
  242.      *
  243.      * @param key  the key to find the index of
  244.      * @return the index, or -1 if not found
  245.      */
  246.     public int indexOf(Object key) {
  247.         key = convertKey(key);
  248.         int i = 0;
  249.         for (LinkEntry<K, V> entry = header.after; entry != header; entry = entry.after, i++) {
  250.             if (isEqualKey(key, entry.key)) {
  251.                 return i;
  252.             }
  253.         }
  254.         return CollectionUtils.INDEX_NOT_FOUND;
  255.     }

  256.     /**
  257.      * Deserializes the map in using a custom routine.
  258.      *
  259.      * @param in the input stream
  260.      * @throws IOException if an error occurs while reading from the stream
  261.      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
  262.      */
  263.     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
  264.         in.defaultReadObject();
  265.         doReadObject(in);
  266.     }

  267.     /**
  268.      * Removes the element at the specified index.
  269.      *
  270.      * @param index  the index of the object to remove
  271.      * @return the previous value corresponding the {@code key},
  272.      *  or {@code null} if none existed
  273.      * @throws IndexOutOfBoundsException if the index is invalid
  274.      */
  275.     public V remove(final int index) {
  276.         return remove(get(index));
  277.     }

  278.     /**
  279.      * Serializes this object to an ObjectOutputStream.
  280.      *
  281.      * @param out the target ObjectOutputStream.
  282.      * @throws IOException thrown when an I/O errors occur writing to the target stream.
  283.      */
  284.     private void writeObject(final ObjectOutputStream out) throws IOException {
  285.         out.defaultWriteObject();
  286.         doWriteObject(out);
  287.     }

  288. }