使用map的簡單實例如下:
demo1:Java
package encapsulation; /** * Created by 黃天柱 on 2016/11/13. */ import java.util.HashMap; import java.util.Map; public class MAP { public static void main(String[] args){ Map<String, String> map = new HashMap<String, String>();//創建map對象 String key1 = "james"; String key2 = "justin"; String key3 = "24"; String key4 = "3"; //初始化 map.put(key1, "james"); map.put(key2, "cto"); map.put(key3, "34"); map.put(key4, "10"); //爲key賦值 System.out.println(map.get(key1)); System.out.println(map.get(key2)); System.out.println(map.get(key3)); System.out.println(map.get(key4)); } }
demo2:Java
package encapsulation; import java.util.Map; import java.util.HashMap; import java.util.Map.Entry; /** * Created by 黃天柱 on 2016/11/12. */ public class HashmapTest { public static void main(String[] args){ Map<Person, String>testMap=new HashMap<Person,String>(); Person p1=new Person(); p1.setName("jakie"); p1.setHeight(165); Person p2=new Person(); p2.setName("Jerry"); p2.setHeight(175); Person p3=new Person(); p3.setName("Bob"); p3.setHeight(160); System.out.println(p1+"hashcode"+p1.hashCode()+"\n"); System.out.println(p2+"hashcode"+p2.hashCode()+"\n"); System.out.println(p3+"hashcode"+p3.hashCode()+"\n"); System.out.println("***********"); System.out.println("putting object into map"); testMap.put(p1,"p1"); testMap.put(p2,"p2"); testMap.put(p3,"p3"); System.out.println("************"); System.out.println(p2+"Jerry is now kelly"); System.out.println("P2 hashcode after update:"); System.out.println(p2+";hashcode:"+p2.hashCode()+"\n"); System.out.println("****************"); System.out.println("Hashcode of elements in HashMap"); for (Entry<Person,String>entry:testMap.entrySet()){ System.out.println(entry.getKey()+":"+entry.getValue()+":"+entry.getKey().hashCode()); System.out.println(); if (entry.getKey().getName().equals("Jakie")){ System.out.println("jakie in map is the original jakie"+(entry.getKey()==p1)); }else if (entry.getKey().getName().equals("Jerry is now Kelly") ){ System.out.println("Jerry is now kelly in map is the original Jerry "+(entry.getKey()==p2)); } } System.out.println("*******************"); String p=testMap.get(p2); System.out.println("Final Result :"+p); } }
demo3:JavaScript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript Array map Method</title> </head> <body> <script type="text/javascript"> if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) res[i] = fun.call(thisp, this[i], i, this); } return res; }; } var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); document.write("roots is : " + roots ); </script> </body> </html>