HashMap
它根据键的hashCode值存储数据,大多数情况下可以直接定位到它的值,因而具有很快的访问速度,但遍历顺序却是不确定的。 HashMap最多只允许一条记录的键为null,允许多条记录的值为null。HashMap非线程安全,即任一时刻可以有多个线程同时写HashMap,可能会导致数据的不一致。如果需要满足线程安全,可以用 Collections的synchronizedMap方法使HashMap具有线程安全的能力,或者使用ConcurrentHashMap。
HashMap中如果键为自定义类,则自定义类中需要重写hashCode()和equals()方法。为了判断键的内容是否一致
public class HashMapDemo4 { public static void main(String[] args) { //创建集合对象 HashMap<Student, String> map = new HashMap<Student,String>() ; //创建学生对象 Student s1 = new Student("aa", 27) ; Student s2 = new Student("abc", 35) ; Student s3 = new Student("vad", 30) ; Student s4 = new Student("bb",28) ; Student s5 = new Student("aa", 27) ; //添加元素 map.put(s1, "qw") ; map.put(s2, "qe") ; map.put(s3, "qr") ; map.put(s4, "ce") ; map.put(s5, "cr") ; //遍历 Set<Student> set = map.keySet() ; for(Student s :set) { String value = map.get(s) ; System.out.println(s.getName()+"---"+s.getAge()+"---"+value); } } }
自定义类
public class Student { private String name ; private int age ; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } // 重写hashCode()和equals()方法 @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Student)) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }