Java集合框架讲解

java集合框架

java.util包提供了一些集合类。这些集合类又被称为容器。提到集合又会想到数组,集合类与数组的不同之处是:数组的长度是固定的,集合的长度是可变的;数组用来存放基本类型的数据,集合用来存放对象的引用。常用的集合用List集合、Set集合、Map集合。其中set和list继承了Collection接口,各接口还提供了不同的实现类。
如图(图片源于网络):

Java集合框架讲解_第1张图片

Map集合

Map集合没有继承collection接口,其提供的是key到value的映射。Map中不能包含相同的key,每个key只能映射一个value。key还决定了存储对象在映射中存在的位置,但不是有key对象本身决定的,而是通过一种“散列技术”进行处理,产生一个散列码的整数值。散列码通常用作一个偏移量,该偏移量对应分配给映射的内存区域的起始位置,从而确定存储对象咋映射中的存储位置。Map集合包括Map接口以Map接口实现类。
Map接口常用的实现类有HashMap和TreeMap。
map集合源码

package java.util;

import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.io.Serializable;


public interface Map {
    // Query Operations

    /**
     * Returns the number of key-value mappings in this map.  If the
     * map contains more than Integer.MAX_VALUE elements, returns
     * Integer.MAX_VALUE.
     *
     * @return the number of key-value mappings in this map
     */
    int size();

    /**
     * Returns true if this map contains no key-value mappings.
     *
     * @return true if this map contains no key-value mappings
     */
    boolean isEmpty();


    boolean containsKey(Object key);


    boolean containsValue(Object value);


    V put(K key, V value);


    V remove(Object key);



    void putAll(Map m);


    void clear();


    // Views

    /**
     * Returns a {@link Set} view of the keys contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own remove operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * Iterator.remove, Set.remove,
     * removeAll, retainAll, and clear
     * operations.  It does not support the add or addAll
     * operations.
     *
     * @return a set view of the keys contained in this map
     */
    Set keySet();

    /**
     * Returns a {@link Collection} view of the values contained in this map.
     * The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  If the map is
     * modified while an iteration over the collection is in progress
     * (except through the iterator's own remove operation),
     * the results of the iteration are undefined.  The collection
     * supports element removal, which removes the corresponding
     * mapping from the map, via the Iterator.remove,
     * Collection.remove, removeAll,
     * retainAll and clear operations.  It does not
     * support the add or addAll operations.
     *
     * @return a collection view of the values contained in this map
     */
    Collection values();

    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own remove operation, or through the
     * setValue operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the Iterator.remove,
     * Set.remove, removeAll, retainAll and
     * clear operations.  It does not support the
     * add or addAll operations.
     *
     * @return a set view of the mappings contained in this map
     */
    Set> entrySet();

    /**
     * A map entry (key-value pair).  The Map.entrySet method returns
     * a collection-view of the map, whose elements are of this class.  The
     * only way to obtain a reference to a map entry is from the
     * iterator of this collection-view.  These Map.Entry objects are
     * valid only for the duration of the iteration; more formally,
     * the behavior of a map entry is undefined if the backing map has been
     * modified after the entry was returned by the iterator, except through
     * the setValue operation on the map entry.
     *
     * @see Map#entrySet()
     * @since 1.2
     */
    interface Entry {
        /**
         * Returns the key corresponding to this entry.
         *
         * @return the key corresponding to this entry
         * @throws IllegalStateException implementations may, but are not
         *         required to, throw this exception if the entry has been
         *         removed from the backing map.
         */
        K getKey();

        /**
         * Returns the value corresponding to this entry.  If the mapping
         * has been removed from the backing map (by the iterator's
         * remove operation), the results of this call are undefined.
         *
         * @return the value corresponding to this entry
         * @throws IllegalStateException implementations may, but are not
         *         required to, throw this exception if the entry has been
         *         removed from the backing map.
         */
        V getValue();

        /**
         * Replaces the value corresponding to this entry with the specified
         * value (optional operation).  (Writes through to the map.)  The
         * behavior of this call is undefined if the mapping has already been
         * removed from the map (by the iterator's remove operation).
         *
         * @param value new value to be stored in this entry
         * @return old value corresponding to the entry
         * @throws UnsupportedOperationException if the put operation
         *         is not supported by the backing map
         * @throws ClassCastException if the class of the specified value
         *         prevents it from being stored in the backing map
         * @throws NullPointerException if the backing map does not permit
         *         null values, and the specified value is null
         * @throws IllegalArgumentException if some property of this value
         *         prevents it from being stored in the backing map
         * @throws IllegalStateException implementations may, but are not
         *         required to, throw this exception if the entry has been
         *         removed from the backing map.
         */
        V setValue(V value);

        /**
         * Compares the specified object with this entry for equality.
         * Returns true if the given object is also a map entry and
         * the two entries represent the same mapping.  More formally, two
         * entries e1 and e2 represent the same mapping
         * if
         *     (e1.getKey()==null ?
         *      e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &&
         *     (e1.getValue()==null ?
         *      e2.getValue()==null : e1.getValue().equals(e2.getValue()))
         * 
* This ensures that the equals method works properly across * different implementations of the Map.Entry interface. * * @param o object to be compared for equality with this map entry * @return true if the specified object is equal to this map * entry */ boolean equals(Object o); /** * Returns the hash code value for this map entry. The hash code * of a map entry e is defined to be:
         *     (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
         *     (e.getValue()==null ? 0 : e.getValue().hashCode())
         * 
* This ensures that e1.equals(e2) implies that * e1.hashCode()==e2.hashCode() for any two Entries * e1 and e2, as required by the general * contract of Object.hashCode. * * @return the hash code value for this map entry * @see Object#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); /** * Returns a comparator that compares {@link Map.Entry} in natural order on key. * *

The returned comparator is serializable and throws {@link * NullPointerException} when comparing an entry with a null key. * * @param the {@link Comparable} type of then map keys * @param the type of the map values * @return a comparator that compares {@link Map.Entry} in natural order on key. * @see Comparable * @since 1.8 */ public static , V> Comparator> comparingByKey() { return (Comparator> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey()); } /** * Returns a comparator that compares {@link Map.Entry} in natural order on value. * *

The returned comparator is serializable and throws {@link * NullPointerException} when comparing an entry with null values. * * @param the type of the map keys * @param the {@link Comparable} type of the map values * @return a comparator that compares {@link Map.Entry} in natural order on value. * @see Comparable * @since 1.8 */ public static > Comparator> comparingByValue() { return (Comparator> & Serializable) (c1, c2) -> c1.getValue().compareTo(c2.getValue()); } /** * Returns a comparator that compares {@link Map.Entry} by key using the given * {@link Comparator}. * *

The returned comparator is serializable if the specified comparator * is also serializable. * * @param the type of the map keys * @param the type of the map values * @param cmp the key {@link Comparator} * @return a comparator that compares {@link Map.Entry} by the key. * @since 1.8 */ public static Comparator> comparingByKey(Comparator cmp) { Objects.requireNonNull(cmp); return (Comparator> & Serializable) (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); } /** * Returns a comparator that compares {@link Map.Entry} by value using the given * {@link Comparator}. * *

The returned comparator is serializable if the specified comparator * is also serializable. * * @param the type of the map keys * @param the type of the map values * @param cmp the value {@link Comparator} * @return a comparator that compares {@link Map.Entry} by the value. * @since 1.8 */ public static Comparator> comparingByValue(Comparator cmp) { Objects.requireNonNull(cmp); return (Comparator> & Serializable) (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); } } // Comparison and hashing /** * Compares the specified object with this map for equality. Returns * true if the given object is also a map and the two maps * represent the same mappings. More formally, two maps m1 and * m2 represent the same mappings if * m1.entrySet().equals(m2.entrySet()). This ensures that the * equals method works properly across different implementations * of the Map interface. * * @param o object to be compared for equality with this map * @return true if the specified object is equal to this map */ boolean equals(Object o); /** * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * entrySet() view. This ensures that m1.equals(m2) * implies that m1.hashCode()==m2.hashCode() for any two maps * m1 and m2, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this map * @see Map.Entry#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); // Defaultable methods /** * Returns the value to which the specified key is mapped, or * {@code defaultValue} if this map contains no mapping for the key. * * @implSpec * The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param key the key whose associated value is to be returned * @param defaultValue the default mapping of the key * @return the value to which the specified key is mapped, or * {@code defaultValue} if this map contains no mapping for the key * @throws ClassCastException if the key is of an inappropriate type for * this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @since 1.8 */ default V getOrDefault(Object key, V defaultValue) { V v; return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue; } /** * Performs the given action for each entry in this map until all entries * have been processed or the action throws an exception. Unless * otherwise specified by the implementing class, actions are performed in * the order of entry set iteration (if an iteration order is specified.) * Exceptions thrown by the action are relayed to the caller. * * @implSpec * The default implementation is equivalent to, for this {@code map}: *

 {@code
     * for (Map.Entry entry : map.entrySet())
     *     action.accept(entry.getKey(), entry.getValue());
     * }
* * The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param action The action to be performed for each entry * @throws NullPointerException if the specified action is null * @throws ConcurrentModificationException if an entry is found to be * removed during iteration * @since 1.8 */ default void forEach(BiConsumersuper
K, ? super V> action) { Objects.requireNonNull(action); for (Map.Entry entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } action.accept(k, v); } } /** * Replaces each entry's value with the result of invoking the given * function on that entry until all entries have been processed or the * function throws an exception. Exceptions thrown by the function are * relayed to the caller. * * @implSpec *

The default implementation is equivalent to, for this {@code map}: *

 {@code
     * for (Map.Entry entry : map.entrySet())
     *     entry.setValue(function.apply(entry.getKey(), entry.getValue()));
     * }
* *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param function the function to apply to each entry * @throws UnsupportedOperationException if the {@code set} operation * is not supported by this map's entry set iterator. * @throws ClassCastException if the class of a replacement value * prevents it from being stored in this map * @throws NullPointerException if the specified function is null, or the * specified replacement value is null, and this map does not permit null * values * @throws ClassCastException if a replacement value is of an inappropriate * type for this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws NullPointerException if function or a replacement value is null, * and this map does not permit null keys or values * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws IllegalArgumentException if some property of a replacement value * prevents it from being stored in this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ConcurrentModificationException if an entry is found to be * removed during iteration * @since 1.8 */ default void replaceAll(BiFunctionsuper K, ? super V, ? extends V> function) { Objects.requireNonNull(function); for (Map.Entry entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } // ise thrown from function is not a cme. v = function.apply(k, v); try { entry.setValue(v); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } } } /** * If the specified key is not already associated with a value (or is mapped * to {@code null}) associates it with the given value and returns * {@code null}, else returns the current value. * * @implSpec * The default implementation is equivalent to, for this {@code * map}: * *

 {@code
     * V v = map.get(key);
     * if (v == null)
     *     v = map.put(key, value);
     *
     * return v;
     * }
* *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * {@code null} if there was no mapping for the key. * (A {@code null} return can also indicate that the map * previously associated {@code null} with the key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ClassCastException if the key or value is of an inappropriate * type for this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @since 1.8 */ default V putIfAbsent(K key, V value) { V v = get(key); if (v == null) { v = put(key, value); } return v; } /** * Removes the entry for the specified key only if it is currently * mapped to the specified value. * * @implSpec * The default implementation is equivalent to, for this {@code map}: * *

 {@code
     * if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
     *     map.remove(key);
     *     return true;
     * } else
     *     return false;
     * }
* *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param key key with which the specified value is associated * @param value value expected to be associated with the specified key * @return {@code true} if the value was removed * @throws UnsupportedOperationException if the {@code remove} operation * is not supported by this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ClassCastException if the key or value is of an inappropriate * type for this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @since 1.8 */ default boolean remove(Object key, Object value) { Object curValue = get(key); if (!Objects.equals(curValue, value) || (curValue == null && !containsKey(key))) { return false; } remove(key); return true; } /** * Replaces the entry for the specified key only if currently * mapped to the specified value. * * @implSpec * The default implementation is equivalent to, for this {@code map}: * *

 {@code
     * if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
     *     map.put(key, newValue);
     *     return true;
     * } else
     *     return false;
     * }
* * The default implementation does not throw NullPointerException * for maps that do not support null values if oldValue is null unless * newValue is also null. * *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @return {@code true} if the value was replaced * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ClassCastException if the class of a specified key or value * prevents it from being stored in this map * @throws NullPointerException if a specified key or newValue is null, * and this map does not permit null keys or values * @throws NullPointerException if oldValue is null and this map does not * permit null values * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws IllegalArgumentException if some property of a specified key * or value prevents it from being stored in this map * @since 1.8 */ default boolean replace(K key, V oldValue, V newValue) { Object curValue = get(key); if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) { return false; } put(key, newValue); return true; } /** * Replaces the entry for the specified key only if it is * currently mapped to some value. * * @implSpec * The default implementation is equivalent to, for this {@code map}: * *

 {@code
     * if (map.containsKey(key)) {
     *     return map.put(key, value);
     * } else
     *     return null;
     * }
* *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * {@code null} if there was no mapping for the key. * (A {@code null} return can also indicate that the map * previously associated {@code null} with the key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map * @since 1.8 */ default V replace(K key, V value) { V curValue; if (((curValue = get(key)) != null) || containsKey(key)) { curValue = put(key, value); } return curValue; } /** * If the specified key is not already associated with a value (or is mapped * to {@code null}), attempts to compute its value using the given mapping * function and enters it into this map unless {@code null}. * *

If the function returns {@code null} no mapping is recorded. If * the function itself throws an (unchecked) exception, the * exception is rethrown, and no mapping is recorded. The most * common usage is to construct a new object serving as an initial * mapped value or memoized result, as in: * *

 {@code
     * map.computeIfAbsent(key, k -> new Value(f(k)));
     * }
* *

Or to implement a multi-value map, {@code Map>}, * supporting multiple values per key: * *

 {@code
     * map.computeIfAbsent(key, k -> new HashSet()).add(v);
     * }
* * * @implSpec * The default implementation is equivalent to the following steps for this * {@code map}, then returning the current value or {@code null} if now * absent: * *
 {@code
     * if (map.get(key) == null) {
     *     V newValue = mappingFunction.apply(key);
     *     if (newValue != null)
     *         map.put(key, newValue);
     * }
     * }
* *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. In particular, all implementations of * subinterface {@link java.util.concurrent.ConcurrentMap} must document * whether the function is applied once atomically only if the value is not * present. * * @param key key with which the specified value is to be associated * @param mappingFunction the function to compute a value * @return the current (existing or computed) value associated with * the specified key, or null if the computed value is null * @throws NullPointerException if the specified key is null and * this map does not support null keys, or the mappingFunction * is null * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @since 1.8 */ default V computeIfAbsent(K key, Functionsuper K, ? extends V> mappingFunction) { Objects.requireNonNull(mappingFunction); V v; if ((v = get(key)) == null) { V newValue; if ((newValue = mappingFunction.apply(key)) != null) { put(key, newValue); return newValue; } } return v; } /** * If the value for the specified key is present and non-null, attempts to * compute a new mapping given the key and its current mapped value. * *

If the function returns {@code null}, the mapping is removed. If the * function itself throws an (unchecked) exception, the exception is * rethrown, and the current mapping is left unchanged. * * @implSpec * The default implementation is equivalent to performing the following * steps for this {@code map}, then returning the current value or * {@code null} if now absent: * *

 {@code
     * if (map.get(key) != null) {
     *     V oldValue = map.get(key);
     *     V newValue = remappingFunction.apply(key, oldValue);
     *     if (newValue != null)
     *         map.put(key, newValue);
     *     else
     *         map.remove(key);
     * }
     * }
* *

The default implementation makes no guarantees about synchronization * or atomicity properties of this method. Any implementation providing * atomicity guarantees must override this method and document its * concurrency properties. In particular, all implementations of * subinterface {@link java.util.concurrent.ConcurrentMap} must document * whether the function is applied once atomically only if the value is not * present. * * @param key key with which the specified value is to be associated * @param remappingFunction the function to compute a value * @return the new value associated with the specified key, or null if none * @throws NullPointerException if the specified key is null and * this map does not support null keys, or the * remappingFunction is null * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional) * @since 1.8 */ default V computeIfPresent(K key, BiFunctionsuper K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); V oldValue; if ((oldValue = get(key)) != null) { V newValue = remappingFunction.apply(key, oldValue); if (newValue != null) { put(key, newValue); return newValue; } else { remove(key); return null; } } else { return null; } } /** * Attempts to compute a mapping for the specified key and its current * mapped value (or {@code null} if there is no current mapping). For * example, to either create or append a {@code String} msg to a value * mapping: * *

 {@code
     * map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))}pre>
     * (Method {@link #merge merge()} is often simpler to use for such purposes.)
     *
     * <p>If the function returns {@code null}, the mapping is removed (or
     * remains absent if initially absent).  If the function itself throws an
     * (unchecked) exception, the exception is rethrown, and the current mapping
     * is left unchanged.
     *
     * @implSpec
     * The default implementation is equivalent to performing the following
     * steps for this {@code map}, then returning the current value or
     * {@code null} if absent:
     *
     * <pre> {@code
     * V oldValue = map.get(key);
     * V newValue = remappingFunction.apply(key, oldValue);
     * if (oldValue != null ) {
     *    if (newValue != null)
     *       map.put(key, newValue);
     *    else
     *       map.remove(key);
     * } else {
     *    if (newValue != null)
     *       map.put(key, newValue);
     *    else
     *       return null;
     * }
     * }pre>
     *
     * <p>The default implementation makes no guarantees about synchronization
     * or atomicity properties of this method. Any implementation providing
     * atomicity guarantees must override this method and document its
     * concurrency properties. In particular, all implementations of
     * subinterface {@link java.util.concurrent.ConcurrentMap} must document
     * whether the function is applied once atomically only if the value is not
     * present.
     *
     * @param key key with which the specified value is to be associated
     * @param remappingFunction the function to compute a value
     * @return the new value associated with the specified key, or null if none
     * @throws NullPointerException if the specified key is null and
     *         this map does not support null keys, or the
     *         remappingFunction is null
     * @throws UnsupportedOperationException if the {@code put} operation
     *         is not supported by this map
     *         ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional)
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     *         ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional)
     * @since 1.8
     */
    default V compute(K key,
            BiFunctionsuper K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue = get(key);

        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue == null) {
            // delete mapping
            if (oldValue != null || containsKey(key)) {
                // something to remove
                remove(key);
                return null;
            } else {
                // nothing to do. Leave things as they were.
                return null;
            }
        } else {
            // add or replace old mapping
            put(key, newValue);
            return newValue;
        }
    }

    /**
     * If the specified key is not already associated with a value or is
     * associated with null, associates it with the given non-null value.
     * Otherwise, replaces the associated value with the results of the given
     * remapping function, or removes if the result is {@code null}. This
     * method may be of use when combining multiple mapped values for a key.
     * For example, to either create or append a {@code String msg} to a
     * value mapping:
     *
     * <pre> {@code
     * map.merge(key, msg, String::concat)
     * }pre>
     *
     * <p>If the function returns {@code null} the mapping is removed.  If the
     * function itself throws an (unchecked) exception, the exception is
     * rethrown, and the current mapping is left unchanged.
     *
     * @implSpec
     * The default implementation is equivalent to performing the following
     * steps for this {@code map}, then returning the current value or
     * {@code null} if absent:
     *
     * <pre> {@code
     * V oldValue = map.get(key);
     * V newValue = (oldValue == null) ? value :
     *              remappingFunction.apply(oldValue, value);
     * if (newValue == null)
     *     map.remove(key);
     * else
     *     map.put(key, newValue);
     * }pre>
     *
     * <p>The default implementation makes no guarantees about synchronization
     * or atomicity properties of this method. Any implementation providing
     * atomicity guarantees must override this method and document its
     * concurrency properties. In particular, all implementations of
     * subinterface {@link java.util.concurrent.ConcurrentMap} must document
     * whether the function is applied once atomically only if the value is not
     * present.
     *
     * @param key key with which the resulting value is to be associated
     * @param value the non-null value to be merged with the existing value
     *        associated with the key or, if no existing value or a null value
     *        is associated with the key, to be associated with the key
     * @param remappingFunction the function to recompute a value if present
     * @return the new value associated with the specified key, or null if no
     *         value is associated with the key
     * @throws UnsupportedOperationException if the {@code put} operation
     *         is not supported by this map
     *         ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional)
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     *         ("{@docRoot}/java/util/Collection.html#optional-restrictions">optional)
     * @throws NullPointerException if the specified key is null and this map
     *         does not support null keys or the value or remappingFunction is
     *         null
     * @since 1.8
     */
    default V merge(K key, V value,
            BiFunctionsuper V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        Objects.requireNonNull(value);
        V oldValue = get(key);
        V newValue = (oldValue == null) ? value :
                   remappingFunction.apply(oldValue, value);
        if(newValue == null) {
            remove(key);
        } else {
            put(key, newValue);
        }
        return newValue;
    }
}

-Map接口

Map接口提供了将键(key)映射到值(value)对象。一个映射包含重复的key,每个Key最多只能映射到一个值。

-map接口常用方法:

  • put(K key,V value): 向集合中添加指定key与value的映射关系
  • containsKey(Object key):如果此映射包含指定key的映射关系,则返回true
  • containsValue(Object value):如果此映射将一个或多个key映射到指定值,则返回true
  • get(Object key):如果存在指定的key对象,则返回该对象对应的值,否则返回null
  • keyset():返回该集合中所有key对象形成的set集合
  • values():返回集中所有值对象形成的Collection集合
    Map集合中允许值对象时null,而且没有个数限制。

    HashMap

  • HashMap类是基于hash表的Map接口实现,此实现提供所有可选的映射操作,并允许使用null值和null键,但必须保证键的唯一性。HashMap通过哈希表对应期内部的映射关系进行快速查找。此类不保证映射顺序,特别是它不保证该顺序恒久不变。

    TreeMap

  • TreeMap不仅实现类了Map接口,还实现了java.util.SortedMap接口,因此,集合中的映射关系具有一定的顺序。但在添加、删除和定位对应的关系时,TreeMap类实现的Map集合中映射关系时根据键对象按照一定的顺序排列的,因此不允许键对象为null.
    注:可以通过HashMap类创建Map集合,当需要顺序输出时,再创造一个完成相同映射关系的TreeMap类实例
    List接口
  • List集合中的元素允许重复各元素的顺序就是对象插入的顺序。
    List中常用的方法:

  • get(int index):获得指定索引位置的元素

  • set(int index,Object obj):将指定索引位置的对象改为指定的对象

ArrayList

  • ArrayList是List接口的实现类是基于Object[] array来实现的。它会在内存中开辟一块连续的空间来存储。由于数据存储也是连续的,因此,支持使用序号(下标。索引)来访问元素,同时,索引输的速度比较快。但是在元素插入的时候需要移动容器中所有的元素,因此,造成插入速度较慢。

LinkedList

  • LinkedList是采用双向列表的实现的,对数据的索引需要从列表头开始遍历,因此,随机访问的效率比较低,但是插入元素的时候不需要对数据进行移动,插入效率较高。同时,LinkedList不是线程安全的。

Set接口

Set接口中的元素不按特定的顺序排序。只是简单地把对象加入集合中,但是Set集合不能包含重复的对象
Set的构造器有个一约束条件,传入的Collection对象不能有重复的值,必须小心操作可变对象(Mutable Object)。如果有一个Set中的可变元素改变了自身的转态导致Object.equals(Object) == true,则会出现一些问题。

TreeSet

TreeSet类不仅实现了Set接口,还实现了java.util.SortedSet接口,因此,TreeSet类实现的Set集合在遍历集合是会按照自然顺序递增排序,也可以按照指定比较器递增排序,即可以通过比较器对用TreeSet类实现的Set集合中的对象进行排序。

HashSet

HashSet实现Set接口,由哈希表(实际上是一个HashMap实例)支持。它不保证set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用null元素

  • 具体的看java源码

HashSet代码块

package java.util;

import java.io.InvalidObjectException;
import sun.misc.SharedSecrets;


public class HashSet
    extends AbstractSet
    implements Set, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap map;


    private static final Object PRESENT = new Object();


    public HashSet() {
        map = new HashMap<>();
    }


    public HashSet(Collection c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }


    public HashSet(int initialCapacity, float loadFactor) {
        map = new HashMap<>(initialCapacity, loadFactor);
    }


    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }


    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }


    public Iterator iterator() {
        return map.keySet().iterator();
    }


    public int size() {
        return map.size();
    }


    public boolean isEmpty() {
        return map.isEmpty();
    }


    public boolean contains(Object o) {
        return map.containsKey(o);
    }


    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }


    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

    /**
     * Removes all of the elements from this set.
     * The set will be empty after this call returns.
     */
    public void clear() {
        map.clear();
    }


    @SuppressWarnings("unchecked")
    public Object clone() {
        try {
            HashSet newSet = (HashSet) super.clone();
            newSet.map = (HashMap) map.clone();
            return newSet;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }


    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out HashMap capacity and load factor
        s.writeInt(map.capacity());
        s.writeFloat(map.loadFactor());

        // Write out size
        s.writeInt(map.size());

        // Write out all elements in the proper order.
        for (E e : map.keySet())
            s.writeObject(e);
    }

    /**
     * Reconstitute the HashSet instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read capacity and verify non-negative.
        int capacity = s.readInt();
        if (capacity < 0) {
            throw new InvalidObjectException("Illegal capacity: " +
                                             capacity);
        }

        // Read load factor and verify positive and non NaN.
        float loadFactor = s.readFloat();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        }

        // Read size and verify non-negative.
        int size = s.readInt();
        if (size < 0) {
            throw new InvalidObjectException("Illegal size: " +
                                             size);
        }
        // Set the capacity according to the size and load factor ensuring that
        // the HashMap is at least 25% full but clamping to maximum capacity.
        capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
                HashMap.MAXIMUM_CAPACITY);

        // Constructing the backing map will lazily create an array when the first element is
        // added, so check it before construction. Call HashMap.tableSizeFor to compute the
        // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
        // what is actually created.

        SharedSecrets.getJavaOISAccess()
                     .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));

        // Create backing HashMap
        map = (((HashSet)this) instanceof LinkedHashSet ?
               new LinkedHashMap(capacity, loadFactor) :
               new HashMap(capacity, loadFactor));

        // Read in all elements in the proper order.
        for (int i=0; i"unchecked")
                E e = (E) s.readObject();
            map.put(e, PRESENT);
        }
    }


    public Spliterator spliterator() {
        return new HashMap.KeySpliterator(map, 0, -1, 0, 0);
    }
}

你可能感兴趣的:(java核心)