LinkedHashMap 集合
一、Map集合的继承体系
- Map
- TreeMap
- HashMap
- LinkedHashMap
二、数据结构
- 链表 + 哈希表
- 链表:保证数据是有序的,添加顺序和迭代顺序是一致的
- 哈希表:保证键是唯一的(去重的作用)
三、代码演示
- LinkedHashMap集合与HashMap集合的区别在于LinkedHashMap集合传入和遍历出的顺序是相同
//Person.java
package com.map.demo2;
public class Person {
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
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;
}
@Override
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;
}
@Override
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;
}
}
//LinkedHashMapTest.java
package com.map.demo3;
import java.util.LinkedHashMap;
import java.util.Set;
public class LinkedHashMapTest {
public static void main(String[] args) {
LinkedHashMap<String, Person> map = new LinkedHashMap<String, Person>();
Person p1 = new Person("张三", 18);
Person p2 = new Person("李四", 19);
Person p3 = new Person("王五", 20);
Person p4 = new Person("赵六", 21);
Person p5 = new Person("马七", 22);
map.put("001", p1);
map.put("002", p2);
map.put("003", p3);
map.put("004", p4);
map.put("005", p5);
Set<String> keySet = map.keySet();
for (String key : keySet) {
Person person = map.get(key);
System.out.println(key + "-----" + person);
}
}
}
- 执行结果:
001-----Person [name=张三, age=18]
002-----Person [name=李四, age=19]
003-----Person [name=王五, age=20]
004-----Person [name=赵六, age=21]
005-----Person [name=马七, age=22]