-
Map集合的实现类
HashMap 【重点】:
-
JDK1.2版本,线程不安全,运行效率快;允许用null 作为Key或是value。
-
案例
/* * HashMap集合的使用 * 存储结构:哈希表(链表+数组+红黑树) * */ import java.util.HashMap; import java.util.Map; public class HashMapTest { public static void main(String[] args) { //创建集合 HashMap<Student, String> hashMap = new HashMap<Student, String>(); //1.添加元素 Student s1=new Student("张三",11); Student s2=new Student("李四",12); Student s3=new Student("王五",13); hashMap.put(s1,"武汉"); hashMap.put(s2,"南京"); hashMap.put(s3,"北京"); hashMap.put(s3,"海南"); //Key相等的情况下 后面的会把前面的覆盖 hashMap.put(new Student("王五",13),"海南"); //HashMap 是根据Key的hashcode和equals作为依据判断是否重复 如果重写了Hashcode和equals 就不能添加进去了 System.out.println("元素个数:"+hashMap.size()); System.out.println(hashMap.toString()); //2.删除 // hashMap.remove(new Student("李四",12)); // // System.out.println("元素个数:"+hashMap.size()); // System.out.println(hashMap.toString()); //3.遍历 System.out.println("-----------keySet--------------"); for (Student student : hashMap.keySet()) { System.out.println(student.toString()+"------------"+hashMap.get(student)); } System.out.println("-----------entrySet------------"); for (Map.Entry<Student, String> stringEntry : hashMap.entrySet()) { //System.out.println(stringEntry); System.out.println(stringEntry.getKey()+"----------"+stringEntry.getValue()); } //4.判断 System.out.println(hashMap.containsKey(s1)); System.out.println(hashMap.containsValue("海南")); } }
实体类
public class Student { private String name; private int aga; public Student(String name, int aga) { this.name = name; this.aga = aga; } public Student() { } public String getName() { return name; } public int getAga() { return aga; } public void setName(String name) { this.name = name; } public void setAga(int aga) { this.aga = aga; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", aga=" + aga + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return aga == student.aga && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, aga); } }
-
Java中的HashMap 【理论+案例】
最新推荐文章于 2022-05-08 07:15:00 发布