首页 > 其他分享 >HashMap的使用

HashMap的使用

时间:2023-02-20 18:45:22浏览次数:27  
标签:stuNo name Student 使用 println HashMap public hashMap

package edu.wtbu;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Demo01 {
public static void main(String[] args) {
//HashMap集合的使用:存储结构:哈希表(数组+链表+红黑树)
//使用key的hashCode和equals作为重复

//创建集合
HashMap<Student, String> hashMap = new HashMap<>();

//1.添加元素
Student s1 = new Student("张三", 16);
Student s2 = new Student("李四", 17);
Student s3 = new Student("王五", 18);
hashMap.put(s1,"湖北");
hashMap.put(s2,"湖南");
hashMap.put(s3,"深圳");
//hashMap.put(s3,"上海");
hashMap.put(new Student("王五", 18),"深圳");
System.out.println("元素个数:"+hashMap.size());//元素个数:3
System.out.println(hashMap);//{Student{name='王五', stuNo=18}=深圳, Student{name='张三', stuNo=16}=湖北, Student{name='李四', stuNo=17}=湖南}

//2.删除元素
hashMap.remove(s1);
System.out.println("元素个数:"+hashMap.size());//元素个数:2
System.out.println(hashMap);//{Student{name='王五', stuNo=18}=深圳, Student{name='李四', stuNo=17}=湖南}

//3.遍历
//1.使用KeySet
Set<Student> keySet = hashMap.keySet();
for (Student key:
keySet) {
System.out.println(key+"--------"+hashMap.get(key));
}

//2.使用EntrySet
Set<Map.Entry<Student, String>> entrySet = hashMap.entrySet();
for (Map.Entry<Student, String> entry:
entrySet) {
//System.out.println(entry.getKey()+"-----------"+entry.getValue());
System.out.println(entry);
}

//4.判断
System.out.println(hashMap.containsKey(s2));//true
System.out.println(hashMap.isEmpty());//false

}
}


package edu.wtbu;

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;
}

public int getStuNo() {
return stuNo;
}

public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", stuNo=" + stuNo +
'}';
}

@Override
public 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);
}

@Override
public int hashCode() {
return Objects.hash(name, stuNo);
}
}

标签:stuNo,name,Student,使用,println,HashMap,public,hashMap
From: https://www.cnblogs.com/123456dh/p/17138495.html

相关文章