计算机二级JAVA实例编程练习题1(附答案)
来源:优易学  2011-10-29 11:59:49   【优易学:中国教育考试门户网】   资料下载   IT书店
  题目:
  对java.util.map进行删除其中一键值对操作。
  答:
  /**
  *
  */
  package map;
  import java.util.Collection;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Set;
  /**
  * Delete key-value of an HashMap
  */
  public class HashMapTest {
  /**
  * @param args
  * @throws InterruptedException
  */
  public static void main(String[] args) {
  //construct an map
  HashMap<Integer, String> map=new HashMap<Integer, String>();
  map.put(11, "aa");
  map.put(22, "bb");
  map.put(33, "cc");
  map.put(44, "dd");
  //out print map
  outPrintMap(map);
  //define the value will be deleted
  String deleteValue="cc";
  //get which key
  if (map.containsValue(deleteValue)) {
  Integer key=null;
  for(Iterator<Integer> keys = map.keySet().iterator();keys.hasNext();) {
  Integer index=keys.next();
  if (map.get(index).equals(deleteValue)) {
  key=index;
  System.out.println("You want to delete value:"+deleteValue+", which key is:"+key);
  }
  }
  //remove
  if (key!=null) {
  map.remove(key);
  }
  }else{
  System.out.println("Your delete value"+deleteValue+" is not exist in this map!");
  }
  //out print map
  outPrintMap(map);
  }
  /**
  * Out print an map
  * @param map
  */
  public static void outPrintMap(HashMap<Integer, String> map){
  /**
  * keySet
  */
  Set<Integer> set=map.keySet();
  Iterator<Integer> it=set.iterator();
  while(it.hasNext()){
  System.out.println(it.next());
  }
  /**
  * values
  */
  Collection<String> col=map.values();
  Iterator<String> it1=col.iterator();
  while(it1.hasNext()){
  System.out.println(it1.next());
  }
  }
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训