码迷,mamicode.com
首页 > 其他好文 > 详细

插播一条:Map.Entry

时间:2020-11-21 11:53:59      阅读:3      评论:0      收藏:0      [点我收藏+]

标签:lan   映射   hang   ati   ali   接口   equals   ref   image   

参考链接:https://www.yiibai.com/java/java_mapentry_interface.html

结合源码看教程。

1. 以下源码是Map类的视图方法

Map接口声明的entrySet()方法返回包含映射条目(entry)的Set,这些set元素中的每一个都是Map.Entry对象。

    // 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. 
* (set集合是由映射支持的,因此对映射的更改会反映在集合中,反之亦然.)
* If the map is modified * while an iteration over the set is in progress (except through * the iterator‘s own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * *
@return a set view of the keys contained in this map */ Set<K> 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 <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * * @return a collection view of the values contained in this map */ Collection<V> 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 <tt>remove</tt> operation, or through the * <tt>setValue</tt> 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 <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * * @return a set view of the mappings contained in this map */ Set<Map.Entry<K, V>> entrySet();

2. Map.Entry是Map的一个内部接口:

看这个类注释。

    /**
     * A map entry (key-value pair).  The <tt>Map.entrySet</tt> method returns
     * a collection-view of the map, whose elements are of this class.  The
     * <i>only</i> way to obtain a reference to a map entry is from the
     * iterator of this collection-view.  These <tt>Map.Entry</tt> objects are
     * valid <i>only</i> 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 <tt>setValue</tt> operation on the map entry.
     *
     * @see Map#entrySet()
     * @since 1.2
     */
    interface Entry<K,V> {
        /**
         * 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
         * <tt>remove</tt> 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();

        /**将此映射条目的值设置为value,下面几个异常情况看一下。
         * 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 <tt>remove</tt> operation).
         *
         * @param value new value to be stored in this entry
         * @return old value corresponding to the entry
         * @throws UnsupportedOperationException if the <tt>put</tt> operation
         *         is not supported by the backing map
*   如果无法更改映射,抛UnsupportedOperationException异常。 *
@throws ClassCastException if the class of the specified value * prevents it from being stored in the backing map
*   如果value不是映射的正确类型,抛ClassCastException异常。 *
@throws NullPointerException if the backing map does not permit * null values, and the specified value is null
*    如果value是null并且映射不允许空键,抛NullPointerException异常。 *
@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); /**如果o是一个Map.Entry,其键和值等于其调用对象的值,返回true。 * Compares the specified object with this entry for equality. * Returns <tt>true</tt> if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping * if<pre> * (e1.getKey()==null ? * e2.getKey()==null : e1.getKey().equals(e2.getKey())) &amp;&amp; * (e1.getValue()==null ? * e2.getValue()==null : e1.getValue().equals(e2.getValue())) * </pre> * This ensures that the <tt>equals</tt> method works properly across * different implementations of the <tt>Map.Entry</tt> interface. * * @param o object to be compared for equality with this map entry * @return <tt>true</tt> 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 <tt>e</tt> is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode()) * </pre> * This ensures that <tt>e1.equals(e2)</tt> implies that * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries * <tt>e1</tt> and <tt>e2</tt>, as required by the general * contract of <tt>Object.hashCode</tt>. * * @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. * * <p>The returned comparator is serializable and throws {@link * NullPointerException} when comparing an entry with a null key. * * @param <K> the {@link Comparable} type of then map keys * @param <V> 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 <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey()); } /** * Returns a comparator that compares {@link Map.Entry} in natural order on value. * * <p>The returned comparator is serializable and throws {@link * NullPointerException} when comparing an entry with null values. * * @param <K> the type of the map keys * @param <V> 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 <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getValue().compareTo(c2.getValue()); } /** * Returns a comparator that compares {@link Map.Entry} by key using the given * {@link Comparator}. * * <p>The returned comparator is serializable if the specified comparator * is also serializable. * * @param <K> the type of the map keys * @param <V> 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 <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); } /** * Returns a comparator that compares {@link Map.Entry} by value using the given * {@link Comparator}. * * <p>The returned comparator is serializable if the specified comparator * is also serializable. * * @param <K> the type of the map keys * @param <V> 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 <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); } }

 3. 差不多了,来一个使用实例:

 

package com.njcx.huffman;

import java.awt.image.BandCombineOp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class testMapEntry {
    public static void main(String[] args) {
        //创建一个hashMap 这个案例没有用泛型
        HashMap hm = new HashMap();
        
        //放元素
        hm.put("i", new Double(134.13));
        hm.put("confused", new Double(123.34));
        hm.put("why", new Double(479.10));
        hm.put("it can run", new Double(299.02));
        hm.put("successfully", new Double(-117.88));
        
        //获取集合项
        Set set = hm.entrySet();
        
        //获取集合迭代器
        Iterator i = set.iterator();
        
        //显示所有元素
        //i.hasNext() returns true if the iteration has more elements
        while(i.hasNext()){
            Map.Entry me = (Map.Entry)i.next();
            System.out.print(me.getKey()+":");
            System.out.println(me.getValue());
        }
        System.out.println();
        
        //添加指定用户积分
        double balance = ((Double)hm.get("i")).doubleValue();//doubleValue():返回值(double类型对象的double类型的值,废话)
        hm.put("i", new Double(balance+1000));
        System.out.println("i的最新积分:"+hm.get("i"));
    }

}

 

插播一条:Map.Entry

标签:lan   映射   hang   ati   ali   接口   equals   ref   image   

原文地址:https://www.cnblogs.com/isayruby/p/13991832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!