Java HashMap练习
JDK1.2添加,线程不安全,性能相对较好
注意:允许使用null作为key或者value
使用数组加链表结构,结合数组和链表的优点
Hash Map的基本使用
package HashMap;import text5.Student;import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;public class Text1 {public static void main(String[] args) {HashMap<String, Student> map = new HashMap<String, Student>();map.put("zhangsan",new Student(1,"张三",16));map.put("lisi",new Student(2,"李四",17));map.put("wangwu",new Student(3,"王五",18));System.out.println(map);//获取元素Student student = map.get("lisi");System.out.println(student);//删除元素
// Student lisi = map.remove("lisi");int size = map.size();System.out.println(size);//得到key集合的遍历(推荐使用的遍历方式)Set<String> set = map.keySet();for (String key : set){System.out.println("键为:"+key + ",值为="+map.get(key));}//直接得到值集Collection<Student> values = map.values();for(Student i : values){System.out.println(i);}//添加相同的key的元素,值会覆盖map.put("lisi",new Student(2,"小李",17));//当添加的对象内容相同时,如果希望其覆盖,应该重写hashcode和equals方法//得到键值的集合Set<Map.Entry<String, Student>> entries = map.entrySet();for(Map.Entry<String, Student> entry : entries){System.out.println("键为:"+entry.getKey() + ",值为="+entry.getValue());}}
}