作者:勇胆识_156 | 来源:互联网 | 2023-10-11 18:16
HashMap存储自定义类型键值1、当给HashMap中存放自定义对象时,如果自定义对象是键存在,保证键唯一,必须复写对象的hashCode和equals方法。2、如果要保证map
HashMap存储自定义类型键值
1、当给HashMap中存放自定义对象时,如果自定义对象是键存在,保证键唯一,必须复写对象的hashCode和equals方法。
2、如果要保证map中存放的key和取出的顺序一致,可使用LinkedHashMap集合来存放
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
//有参构造
this.name = name;
this.age = age;
}//无参构造
public Person() {
super();
}
//get set
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;
}
//toString方法
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
//哈西和equals
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
public class Demo03 {
public static void main(String[] args) {
Map
map=new HashMap
();
map.put(new Person("胸大",22),"java0322班");
map.put(new Person("胸二",20), "java0222班");
map.put(new Person("胸二",20), "java0262班");
//遍历
//1.获取装有所有key的Set集合
Set
set=map.keySet();
//2.遍历set集合取到每一个key
for(Person key:set){
System.out.println(key+"..."+map.get(key));
}
}
}
LinkedHashMap
public class Demo04 {
public static void main(String[] args) {
Map map=new LinkedHashMap();
//添加数据
map.put("java0322",new Person("胸三",33));
map.put("java0222",new Person("胸大",33));
map.put("java0611",new Person("胸三",33));
//遍历(entrySet迭代器)
//1.获取所有结婚证存在的集合
Set> set=map.entrySet();
//2.获取迭代器对象
Iterator> it=set.iterator();
//3.循环判断下个元素是否有值
while(it.hasNext()){
//4.获取每一个结婚证对象
Map.Entry entry=it.next();
//5.从结婚证对象中获取key
String key=entry.getKey();
//6.从结婚证对象中获取value
Person value=entry.getValue();
System.out.println(key+"..."+value);
}
}
}