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;
}
//保证键的唯一性,重写equals()和hashCode()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
//测试类
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDeom {
public static void main(String[] args) {
Map<String, Student> map = new HashMap<>();
Student c1 = new Student("张三", 16);
Student c2 = new Student("李四", 14);
Student c3 = new Student("王五", 17);
Student c4 = new Student("赵六", 16);
map.put("001", c1);
map.put("002", c2);
map.put("003", c3);
map.put("004", c4);
//键找值
Set<String> m = map.keySet();
for (String k : m) {
Student student = map.get(k);
System.out.println(k + "," + student.getName() + "," + student.getAge());
}
System.out.println("-----------");
//键值对对象找键和值
final Set<Map.Entry<String, Student>> entries = map.entrySet();
for (Map.Entry<String, Student> f:entries) {
String key = f.getKey();
System.out.println(key+","+f.getValue().getName()+","+f.getValue().getAge());
}
}
}
Java中HashMap集合
最新推荐文章于 2023-08-07 21:21:43 发布