Map集合的实现类
- HashMap[重点]
- JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value
package gather;
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 +
'}';
}
}
package gather;
import java.util.HashMap;
import java.util.Map;
/*
HashMap集合的使用
存储结构:(数组+链表+红黑树)
使用key的hashcode和equals作为重复
*/
public class Demo14 {
public static <Stuent> void main(String[] args) {
//创建集合
HashMap<Student, String> students = new HashMap<>();
//1.添加元素
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),"南京");//这样也可以添加,想不这样就重写equals和hashcode
System.out.println(students.size());
System.out.println(students);
//2.删除
students.remove(s1);
System.out.println("删除之后"+students.size());
//3.遍历
//3.1使用keySet();
for (Student key: students.keySet()) {
System.out.println(key+"========="+students.get(key));
}
//3.2使用entrySet();
for (Map.Entry<Student, String> entry:students.entrySet()) {
System.out.println(entry.getKey()+"------"+entry.getValue());
}
//4.判断
System.out.println(students.containsKey(s1));
System.out.println(students.containsKey(new Student("孙悟空", 100)));//未重写equals和hashcode判断无
System.out.println(students.containsValue("杭州"));
}
}