该集合存储键值对,一对一对往里面存,而且要保证键的唯一性
添加 put(K key,V value) putAll(Map<? extends K, extends V>m)删除 clear()判断 containsValue(Object value) containsKey(Object key) isEmpty()获取 get(Object key) size() values() entrySet() keySet()底层是哈希表数据结构,不可以存入null键null值,该集合是线程同步的
底层是哈希表数据结构,允许使用null值和null键,该集合是不同步的 (效率高)
底层是二叉树,线程不同步,可以用于给map集合中的键进行排序
每一个学生都有对应的归属地 学生Student,地址String 学生属性:姓名,年龄 注意:姓名和年龄相同视为同一个学生 保证学生的唯一性 1.描述学生 2.定义map容器,将学生作为键,地址作为值,存入 3.获取map集合中的元素
import java.util.*; class student implements Comparable<student> { private String name; private int age; student(String name,int age) { this.name=name; this.age=age; } public int compareTo(student s) { int num = new Integer(this.age).compareTo(new Integer(s.age)); if(num==0) { return this.name.compareTo(s.name); } return num; } public String getName() { return name; } public int getAge() { return age; } public String toString() { return name+":"+age; } public boolean equals(Object obj) { if(!(obj instanceof student)) throw new ClassCastException("类型不匹配"); student s = (student)obj; return this.name.equals(s.name)&&this.age==s.age; } } class maptest { public static void main(String[] args) { HashMap<student,String> hm = new HashMap<student,String>(); hm.put(new student("lisi",21),"beijing"); hm.put(new student("lisi",22),"beijing"); hm.put(new student("lisi",23),"beijing"); hm.put(new student("lisi",24),"beijing"); //第一种取出方式:keyset Set<student> keySet = hm.keySet(); Iterator<student> it = keySet.iterator(); while(it.hasNext()) { student stu=it.next(); String addr = hm.get(stu); System.out.println(stu+"..."+addr); } //第二种取出方式 Set<Map.Entry<student,String>> entryset=hm.entrySået(); Iterator<Map.Entry<student,String>> iter = entryset.iterator(); while(iter.hasNext()) { Map.Entry<student,String> me = iter.next(); student stu = me.getKey(); String addr = me.getValue(); System.out.println(stu+"..."+addr); } } }“sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。 字母和次数之间都有映射关系
import java.util.*; class maptest3 { public static void main(String[] args) { String s = charcount("aabfcdabcdefa"); System.out.println(s); } public static String charcount(String str) { char[] chs = str.toCharArray(); TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(); int count=0; for(int x=0;x<chs.length;x++) { Integer value = tm.get(chs[x]); if(value!=null) count=value; count++; tm.put(chs[x],count); count=0; /* if(value==null) { tm.put(chs[x],1); } else { value = value+1; tm.put(chs[x],value); } */ } StringBuilder sb = new StringBuilder(); Set<Map.Entry<Character,Integer>> entryset = tm.entrySet(); Iterator<Map.Entry<Character,Integer>> it = entryset.iterator(); while(it.hasNext()) { Map.Entry<Character,Integer>me = it.next(); Character ch = me.getKey(); Integer value = me.getValue(); sb.append(ch+"("+value+")"); } return sb.toString(); } }