Map的瞭解

日誌 > 技術交流
設置置頂 | 編輯 | 刪除

Map的瞭解

發表於:2008年3月1日 11時21分48秒閱讀(1)評論(0)本文鏈接:http://user.qzone.qq.com/592433424/blog/1204341708
package map;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* 演示各個Map的實現類
*/
public class TestMap {

/**
  * 初始化一個Map
  * @param map
  */
public static void init(Map map){
  if (map != null){
   String key = null;
   for (int i=5; i>0; i--){
    key = new Integer(i).toString() + ".0";
    map.put(key, key.toString());
    //Map中的鍵是不重複的,如果插入兩個鍵值一樣的記錄,
    //那麼後插入的記錄會覆蓋先插入的記錄
    map.put(key, key.toString() + "0");   }
  }
}
/**
  * 輸出一個Map
  * @param map
  */
public static void output(Map map){
  if (map != null){
   Object key = null;
   Object value = null;
   //使用迭代器遍歷Map的鍵,根據鍵取值
   Iterator it = map.keySet().iterator();
   while (it.hasNext()){
    key = it.next();
    value = map.get(key);
    System.out.println("key: " + key + "; value: " + value );
   }
   //或者使用迭代器遍歷Map的記錄Map.Entry
   Map.Entry entry = null;
   it = map.entrySet().iterator();
   while (it.hasNext()){
    //一個Map.Entry代表一條記錄
    entry = (Map.Entry)it.next();
    //通過entry可以獲得記錄的鍵和值
    //System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
   }
  }
}
/**
  * 判斷map是否包含某個鍵
  * @param map
  * @param key
  * @return
  */
public static boolean containsKey(Map map, Object key){
  if (map != null){
   return map.containsKey(key);
  }
  return false;
}
/**
  * 判斷map是否包含某個值
  * @param map
  * @param value
  * @return
  */
public static boolean containsValue(Map map, Object value){
  if (map != null){
   return map.containsValue(value);
  }
  return false;
}
/**
  * 演示HashMap
  */
public static void testHashMap(){
  Map myMap = new HashMap();
  init(myMap);
  //HashMap的鍵可以爲null
  myMap.put(null,"ddd");
  //HashMap的值可以爲null
  myMap.put("aaa", null);
  output(myMap);
}
/**
  * 演示Hashtable
  */
public static void testHashtable(){
  Map myMap = new Hashtable();
  init(myMap);
  //Hashtable的鍵不能爲null
//  myMap.put(null,"ddd");
//  Hashtable的值不能爲null
//  myMap.put("aaa", null);
  output(myMap);
}
/**
  * 演示LinkedHashMap
  */
public static void testLinkedHashMap(){
  Map myMap = new LinkedHashMap();
  init(myMap);
  //LinkedHashMap的鍵可以爲null
//  myMap.put(null,"ddd");
  //LinkedHashMap的值可以爲null
  myMap.put("aaa", null);
  output(myMap);
}
/**
  * 演示TreeMap
  */
public static void testTreeMap(){
  Map myMap = new TreeMap();
  init(myMap);
  //TreeMap的鍵不能爲null
  //myMap.put(null,"ddd");
  //TreeMap的值不能爲null
  //myMap.put("aaa", null);
  output(myMap);
}
public static void main(String[] args) {
  System.out.println("採用HashMap");
  TestMap.testHashMap();
  System.out.println("採用Hashtable");
  TestMap.testHashtable();
  System.out.println("採用LinkedHashMap");
  TestMap.testLinkedHashMap();
  System.out.println("採用TreeMap");
  TestMap.testTreeMap();
  
  Map myMap = new HashMap();
  TestMap.init(myMap);
  System.out.println("新初始化一個Map: myMap");
  TestMap.output(myMap);
  //清空Map
  myMap.clear();
  System.out.println("將myMap clear後,myMap空了麼?  " + myMap.isEmpty());
  TestMap.output(myMap);
  myMap.put("aaa", "aaaa");
  myMap.put("bbb", "bbbb");
  //判斷Map是否包含某鍵或者某值
  System.out.println("myMap包含鍵aaa?  "+ TestMap.containsKey(myMap, "aaa"));
  System.out.println("myMap包含值aaaa?  "+ TestMap.containsValue(myMap, "aaaa"));
  //根據鍵刪除Map中的記錄
  myMap.remove("aaa");
  System.out.println("刪除鍵aaa後,myMap包含鍵aaa?  "+ TestMap.containsKey(myMap, "aaa"));
  //獲取Map的記錄數
  System.out.println("myMap包含的記錄數:  " + myMap.size());
}
/**
  * Map用於存儲鍵值對,不允許鍵重複,值可以重複。
  * (1)HashMap是一個最常用的Map,它根據鍵的hashCode值存儲數據,根據鍵可以直接獲取它的值,具有很快的訪問速度。
  * HashMap最多隻允許一條記錄的鍵爲null,允許多條記錄的值爲null。
  * HashMap不支持線程的同步,即任一時刻可以有多個線程同時寫HashMap,可能會導致數據的不一致。
  * 如果需要同步,可以用Collections.synchronizedMap(HashMap map)方法使HashMap具有同步的能力。
  * (2)Hashtable與HashMap類似,不同的是:它不允許記錄的鍵或者值爲空;
  * 它支持線程的同步,即任一時刻只有一個線程能寫Hashtable,然而,這也導致了Hashtable在寫入時會比較慢。
  * (3)LinkedHashMap保存了記錄的插入順序,在用Iteraor遍歷LinkedHashMap時,先得到的記錄肯定是先插入的。
  * 在遍歷的時候會比HashMap慢。
  * (4)TreeMap能夠把它保存的記錄根據鍵排序,默認是按升序排序,也可以指定排序的比較器。當用Iteraor遍歷TreeMap時,
  * 得到的記錄是排過序的。
  */
}
 
評論列表
請選擇道具
<textarea class="content" id="commentEditor" style="BORDER-RIGHT: #ccc 1px solid; BORDER-TOP: #ccc 1px solid; BORDER-LEFT: #ccc 1px solid; COLOR: gray! important; BORDER-BOTTOM: #ccc 1px solid" οnfοcus="getUBBeditor(this)" rows="13" cols="50" name="content">點擊這裏發表評論</textarea>
溫馨提示:點擊驗證碼輸入框,以獲取驗證碼
請輸入驗證碼:
     
<script type="text/javascript"> // function jumpToTop() { if(isSmall) { document.body.scrollTop = 0; } else parent.$('mbody').scrollTop = 0; } function _quote(s){ s=s.replace(//[quote/=引自:(.+?)(?:/x20|&nbsp;){1,2}於/x20(.+?)/x20發表的評論/]/g,"/x03引自:<cite>$1</cite>&nbsp;&nbsp;於 <ins>$2</ins> 發表的評論<br />/x02").replace(//[//quote/]/g,"/x01"); for(var i=0;i<2;i++) s=s.replace(//x03([^/x03/x01/x02]*?)/x02([^/x03/x01/x02]*?)/x01/g, function(a,b,c){ return '<blockquote style="width:400px;border:dashed 1px gray;margin:10px;padding:10px">'+b+'引用內容:<br /><br /><q>'+c+'</q></blockquote>'; }); return s.replace(/[/x03/x02/x01]/g,""); } var bLoaded = false; function checkMsgReply(obj) { if(!bLoaded) top.includeJS('/qzone/blog/script/common.js', function(){bLoaded=true;checkMsgReply(obj)}, document); else checkReply(obj); if(obj.checked){ MAX_COMMENT_LEN = 500; } else { MAX_COMMENT_LEN = 4500; } _fontCount = MAX_COMMENT_LEN; //字數限制 if(!window.sendCommentEditor) return; if(sendCommentEditor.editorArea.editMode == 1) toCountFont(sendCommentEditor.id, "html"); else toCountFont(sendCommentEditor.id, "text"); } function showMsgLeftCnt() { if(!bLoaded) top.includeJS('/qzone/blog/script/common.js', function(){bLoaded=true;showMsgLeftCnt();}, document); else showLeftSMS(); } function selectBlogPaper() { if(checkLogin() <= 10000) { top.showLoginBox("mall"); return; } if(!!top.g_JData["blogContent"]) { if(parent.g_iLoginUin == parent.g_iUin) { location.href="/qzone/newblog/blogeditor.html?paperid=" + parent.g_JData["blogContent"].data.lp_id + "&paperstyle=" + parent.g_JData["blogContent"].data.lp_style + "&paperdialog=1"; } else { parent.location.href="http://user.qzone.qq.com/" + parent.g_iLoginUin + "/addNewBlog?paperid=" + parent.g_JData["blogContent"].data.lp_id + "&paperstyle=" + parent.g_JData["blogContent"].data.lp_style; } } else { top.showMsgBox("抱歉,暫時無法獲取該信紙信息!", 1, 2000); } } /** * 批量刪除中選擇全選 */ function selectAllComments(bChecked) { var oList = document.getElementsByName("commentCheckBox"); if(oList.length==0) return; for(var i=0; i<oList.length; ++i){ oList[i].checked = !!bChecked; } } function showCommentCheckBoxs(bShow, bCheck){ var oList = document.getElementsByName("commentCheckBox"); if(oList.length==0) return; for(var i=0; i<oList.length; ++i){ oList[i].style.display = ((!!bShow) ? "" : "none"); if(!!bCheck) oList[i].checked = true; else oList[i].checked = false; } if(!!bCheck) $("batchSelAllInput").checked = true; else $("batchSelAllInput").checked = false; $("leftDeleteComParag").style.display = ((!!bShow) ? "" : "none"); $("batchDelComHref").style.display = ((!!bShow) ? "none" : ""); $("noBatchDelComHref").style.display = ((!!bShow) ? "" : "none"); } /** * 名博批量刪除評論 */ function deleteBatchComments() { if(!contentProperty) return; var oList = document.getElementsByName("commentCheckBox"); if(oList.length==0) { return; } var tmp; var strCommentList = ''; var strArchList = ''; var nDeleteCnt = 0; for(var i=0; i<oList.length; ++i){ if(oList[i].checked) { tmp = oList[i].value.split('_') strCommentList += ('-' + tmp[0]); strArchList += ('-' + tmp[1]); ++nDeleteCnt; } } strCommentList = strCommentList.substr(1); strArchList = strArchList.substr(1); if(nDeleteCnt == 0) { parent.showMsgbox("請選擇要刪除的評論", 0, 2000); return; } if(!!contentProperty && contentProperty.totalCommentNumber < nDeleteCnt) return; if(!confirm("您是否要刪除選中的用戶評論?")) return; parent.loadXMLAsyncNoCache("delBatchReply", "http://"+BLOG_DOMAIN+CGI_PATH+"blog_batch_del_comment", function(){ if(parent.g_XDoc["delBatchReply"].selectNodes("error").length > 0){ dalert(null, parent.g_XDoc["delBatchReply"].xml, 2000); delete parent.g_XDoc["delBatchReply"]; return; } dalert(null, parent.g_XDoc["delBatchReply"].xml, 2000, 2); contentProperty.totalCommentNumber -= nDeleteCnt; //清理cache with(contentProperty){ delete parent.g_XDoc["blogRoot"].contentHSList[currentBlogid]; pageList = {}; pageIndexMap = []; currentCommentPage = lastCommentPage = (!contentProperty.nowaPage)?0:nowaPage[3]; parent.g_XDoc["blogRoot"].replyNumUpdateHSmap[currentBlogid] = totalCommentNumber; parent.isRefreshTop = true; if(currentCommentPage == 0) { setTimeout(contentInit, 1000); } else{ var tp = Math.ceil(totalCommentNumber/PAGE_COMMENT_NUM); var num = totalCommentNumber%PAGE_COMMENT_NUM; if(num==0 || currentCommentPage<tp-1) num = PAGE_COMMENT_NUM; getOnePageComment(num, nowaPage[0], nowaPage[1], nowaPage[2], blogCommentListCallback, 1); $("commentCount3").innerHTML = totalCommentNumber; } } delete top.g_XDoc["delBatchReply"]; showCommentCheckBoxs(false, false); }, function(){ dalert(null, BUSY_MSG, 2000); delete parent.g_XDoc["delBatchReply"]; }, "uin="+parent.g_iLoginUin+"&blogid="+contentProperty.currentBlogid+"&archlist="+strArchList.URLencode()+"&replyidlist="+strCommentList.URLencode() ); } /** * 有評論或沒有時顯示/隱藏相關element */ function showElementsAnyReply(bShow) { var strCss = !!bShow ? "" : "none"; if(isStar && parent.g_iUin == parent.g_iLoginUin) { $("starDeleteComDiv").style.display = strCss; } if(parent.g_bBlogShowCheatHint == true) $("commentHintDiv").style.display = strCss; } /** * 關閉提防上當提示信息 */ function closeCheatHint() { parent.g_bBlogShowCheatHint = false; $('commentHintDiv').style.display = 'none'; } setLoginStatus(); var frmComment=document.getElementById("commendForm"); if(!isSmall) document.body.οnkeydοwn=scrollBlog; if((isStar || isBiz) && (top.g_iLoginUin!=top.g_iUin)){ frmComment.hassign.checked=false; $("startToolSelect").style.display="none"; } if(top.g_iLoginUin>10000 && top.g_iLoginUin!=top.g_iUin) { $("msgboardSelfReply").style.display = ""; $("blogSelPaper").title = "我也要使用此信紙寫日誌"; } setTimeout(contentInit,50); // </script>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章