ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

HashMap使用

2026/9/18 6:42:34 拓冰建站 浏览量
HashMap使用
/*** @Description HashMap使用** HashMap 集合的使用* 存储结构 : 哈希表(数组 + 链表 + 红黑树)* @author AI福*/
package com.chapter3;import java.util.HashMap;
import java.util.Map;public class Demo02 {public static void main(String[] args) {//创建集合HashMap<Student,String> students = new HashMap<Student,String>();//添加元素Student s1 = new Student("孙悟空",100);Student s2 = new Student("猪八戒",101);Student s3 = new Student("沙和尚",102);students.put(s1,"北京");students.put(s2,"上海");students.put(s3,"杭州");//students.put(s3,"南京");students.put(new Student("沙和尚",102),"南京");System.out.println("元素个数"+students.size());System.out.println(students.toString());//2.删除/*students.remove(s1);System.out.println("删除之后"+students.size());*///3.遍历//3.1   使用keySet();for(Student key : students.keySet()){System.out.println(key.toString()+"======="+students.get(key));}System.out.println("----------entrySet----------");//3.2   使用entrySet();for(Map.Entry<Student,String> entry : students.entrySet()){System.out.println(entry.getKey()+"--------"+entry.getValue());}//4.判断System.out.println(students.containsKey(new Student("孙悟空",100)));System.out.println(students.containsValue("杭州"));}}
/*** @Description HashMap使用** Student 学生类* @author AI福*/
package com.chapter3;import java.util.Objects;public class Student {private String name;private int stuNo;public Student() {}public Student(String name, int stuNo) {this.name = name;this.stuNo = stuNo;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return stuNo == student.stuNo && Objects.equals(name, student.name);}@Overridepublic int hashCode() {return Objects.hash(name, stuNo);}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", stuNo=" + stuNo +'}';}}