返回顶部

收藏

获得hashtable的集合视图

更多
package cn.outofmemory.snippets.core;

import java.util.Hashtable;
import java.util.Collection;

public class HashtableValuesCollection {

  public static void main(String[] args) {

    // Create a Hashtable and populate it with elements
    Hashtable hashtable = new Hashtable();
    hashtable.put("key_1","value_1");
    hashtable.put("key_2","value_2");
    hashtable.put("key_3","value_3");
    hashtable.put("key_4","value_4");
    hashtable.put("key_5","value_5");

    /* 
      Collection values() operation returns a Collection containing all values in Hashtable. 
      The values collection is backed by the Hashtable thus elements removed from the 
      Collection will also be removed from the originating Hashtable. 
      Nevertheless it is not permitted to add an element to the resultant value set and 
      java.lang.UnsupportedOperationException exception will be thrown in case we try to.
    */
    Collection valuesCollection = hashtable.values();

    System.out.println("valuesCollection contains : " + valuesCollection);

    valuesCollection.remove("value_2");

    System.out.println("after removing value_2 from valuesCollection, valuesCollection contains : " + valuesCollection + " Hashtable contains : " + hashtable);

  }
}

输出:

valuesCollection contains : [value_5, value_4, value_3, value_2, value_1]
after removing value_2 from valuesCollection, valuesCollection contains : [value_5, value_4, value_3, value_1] Hashtable contains : {key_5=value_5, key_4=value_4, key_3=value_3, key_1=value_1}

标签:java,基础

收藏

0人收藏

支持

0

反对

0

发表评论