1 package cn.itcast.p1.map.test; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class MapTest2 { 7 8 public static void main(String[] args) { 9 /* 10 * Map在有映射關系時,可以優先考慮。 11 * 12 * 在查表法中的應用較為多見。 13 */ 14 String week = getWeek(1); 15 16 System.out.println(week); 17 18 System.out.println(getWeekByMap(week)); 19 20 } 21 22 public static String getWeekByMap(String week) { 23 Map<String,String> map = new HashMap<String,String>(); 24 25 map.put("星期一", "Mon"); 26 map.put("星期二", "Tus"); 27 map.put("星期三", "Wes"); 28 map.put("星期日", "Sun"); 29 30 31 return map.get(week); 32 } 33 34 public static String getWeek(int i) { 35 if (i<1 || i>7) 36 throw new RuntimeException("沒有對應的星期"); 37 38 String[] weeks = {"","星期一","星期二","星期三","星期四"}; 39 40 return weeks[i]; 41 } 42 43 }