LinkedHashMap
概述:键值对怎么存的,就怎么取
代码:
package com.xiaoxin.map;
import java.util.LinkedHashMap;
public class Demo5_LinkedHashMap {
public static void main(String[] args) {
LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
lhm.put("张三", 23);
lhm.put("李四", 24);
lhm.put("王五", 25);
lhm.put("赵六", 26);
lhm.put("马七", 27);
System.out.println(lhm);
}
}
输出:
{张三=23, 李四=24, 王五=25, 赵六=26, 马七=27}
TreeMap
用Student类作为键,String作为值
让Student类实现comparable接口:
package com.xiaoxin.bean;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [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;
Student other = (Student) 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;
}
@Override
public int compareTo(Student s) {
int num = this.name.compareTo(s.name);
return num == 0 ? this.age - s.age : num;
}
}
Demo6_TreeMap.java:
package com.xiaoxin.map;
import java.util.TreeMap;
import com.xiaoxin.bean.Student;
public class Demo6_TreeMap {
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>();
tm.put(new Student("李四", 24), "武汉");
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("王五", 25), "上海");
tm.put(new Student("赵六", 26), "东京");
System.out.println(tm);
}
}
输出:
{Student [name=张三, age=23]=北京, Student [name=李四, age=24]=武汉, Student [name=王五, age=25]=上海, Student [name=赵六, age=26]=东京}
或者,定义TreeMap的时候定义一个比较器:
package com.xiaoxin.map;
import java.util.Comparator;
import java.util.TreeMap;
import com.xiaoxin.bean.Student;
public class Demo7_TreeMap {
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName());
return num == 0 ? s1.getAge() - s2.getAge() : num;
}
});
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("李四", 24), "武汉");
tm.put(new Student("王五", 25), "东京");
tm.put(new Student("赵六", 26), "铁岭");
System.out.println(tm);
}
}
输出:
{Student [name=张三, age=23]=北京, Student [name=李四, age=24]=武汉, Student [name=王五, age=25]=东京, Student [name=赵六, age=26]=铁岭}