在API获取HsahMap类的全部信息
实例代码:创建一个Student类和Demo02
package com.map;
public class Student {
private String name;
private int stuNo;
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 + "]";
}
}
package com.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* HashMap集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
*/
public class Demo02 {
public static void main(String[] args) {
//创建集合 key是Student类 value是String类
HashMap<Student, String> students = new HashMap<>();
//new 学生实例对象
Student s1 = new Student("小王", 100);
Student s2 = new Student("小张",101);
Student s3 = new Student("小朱",102);
//1添加元素
students.put(s1,"北京");
students.put(s2,"上海");
students.put(s3,"杭州");
students.put(s3,"南京"); //添加这个s3会覆盖上面的s3 key不允许重复
System.out.println("元素个数"+students.size());
System.out.println(students);
//2删除
students.remove(s1);
System.out.println(students);
//3遍历
//3.1使用keySet()
System.out.println("---------keySet()----- --");
Set<Student> set = students.keySet();
for (Student s : set) {
System.out.println(s);
}
//3.2使用entrySet() Entry是一个映射对 包括一对key和value
System.out.println("---------entrySet()----- --");
Set<Map.Entry<Student, String>> entries = students.entrySet();
for (Map.Entry<Student, String> entry : entries) {
System.out.println(entry.getKey());
}
//4判断
System.out.println(students.containsKey(s3));
System.out.println(students.containsValue("北京"));
}
}
结果:
总结: