Hashmap使用2
package com.tiedandan.集合.Map集合.HashMap使用2; import com.tiedandan.集合.Map集合.HashMap使用.Student; import java.util.HashMap; import java.util.Map; /** * 去除添加 * */ public class HashMapUse { public static void main(String[] args) { HashMap<Student, String> students = new HashMap<>();//键类型是student,值类型是String类型 Student stu1 = new Student("唐僧",1); Student stu2 = new Student("孙悟空",2); Student stu3 = new Student("猪八戒",3); Student stu4 = new Student("沙和尚",4); students.put(stu1,"天宫"); students.put(stu2,"花果山"); students.put(stu3,"高老庄"); students.put(stu4,"流沙河"); students.put(new Student("沙和尚",4),"流沙河");//要想使重复的·对象不会加入到集合当中,需要重写HashCode和equals方法 System.out.println("键值对个数:"+students.size()); System.out.println("========输出键值对的值=========="); System.out.println(students.toString()); //删除 // students.remove(stu4); //遍历 //使用KeySet(); System.out.println("----------使用KeySet();----------"); for (Student student : students.keySet()) { System.out.println(student.toString()+"--------"+students.get(student)); } //使用entryset(); System.out.println("--------------使用entryset();-----------"); for (Map.Entry<Student, String> entry : students.entrySet()) { System.out.println(entry.getKey()+"----"+entry.getValue()); } //判断 System.out.println("-------判断--------"); System.out.println( students.containsKey("沙和尚")); System.out.println( students.isEmpty()); } }
Student类:
package com.tiedandan.集合.Map集合.HashMap使用2; import java.util.Objects; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { 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; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
运行结果:
键值对个数:5
========输出键值对的值==========
{Student{name='猪八戒', age=3}=高老庄, Student{name='沙和尚', age=4}=流沙河, Student{name='孙悟空', age=2}=花果山, Student{name='唐僧', age=1}=天宫, Student{name='沙和尚', age=4}=流沙河}
----------使用KeySet();----------
Student{name='猪八戒', age=3}--------高老庄
Student{name='沙和尚', age=4}--------流沙河
Student{name='孙悟空', age=2}--------花果山
Student{name='唐僧', age=1}--------天宫
Student{name='沙和尚', age=4}--------流沙河
--------------使用entryset();-----------
Student{name='猪八戒', age=3}----高老庄
Student{name='沙和尚', age=4}----流沙河
Student{name='孙悟空', age=2}----花果山
Student{name='唐僧', age=1}----天宫
Student{name='沙和尚', age=4}----流沙河
-------判断--------
false
false