package com.phone.week4;
public class Student2 implements Comparable{
private String name;
private int age;
private double salay;
public double getSalay() {
return salay;
}
public void setSalay(double salay) {
this.salay = salay;
}
public Student2(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 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;
Student2 other = (Student2) 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(Student2 o) {
if(this.getAge()==o.getAge()){
return this.getName().compareTo(o.getName());
}else if(this.getAge()>o.getAge()){
return -1;
}
else{
return 1;
}
}
@Override
public String toString() {
return "Student2 [name=" + name + ", age=" + age + ", salay=" + salay
+ "]";
}
public Student2(String name, int age, double salay) {
super();
this.name = name;
this.age = age;
this.salay = salay;
}
}
package com.phone.week4;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class TestTreeMap {
public static void main(String[] args) {
//把学生做为键,把学生对应的地址做为值
//Map<Student2, String> map = new TreeMap<>();
//Map<Student2, String> map = new TreeMap<>(new MyCompare());
Map<Student2, String> map = new TreeMap<>(new Comparator<Student2>() {
@Override
public int compare(Student2 o1, Student2 o2) {
if(o1.getSalay()==o2.getSalay()){
return 0;
}else if(o1.getSalay()>o2.getSalay()){
return -1;
}else{
return 1;
}
}
});
map.put(new Student2("rainbow", 12,10000), "英国");
map.put(new Student2("amy", 22,20000), "美国");
map.put(new Student2("edward", 43,2000), "埃塞鹅比亚");
map.put(new Student2("bill", 3,50000), "西班牙");
map.put(new Student2("amy", 56,3500), "南非");
map.put(new Student2("amy", 56,5099), "南非");
for (Student2 key : map.keySet()) {
System.out.println(key+"===="+map.get(key));
}
}
private static void test1() {
Map<String, String> map = new TreeMap<>();
map.put("rainbow", "彩虹");
map.put("amy", "艾咪");
map.put("edward", "爱德华");
map.put("bill", "比尔");
for (String key : map.keySet()) {
System.out.println(key+"====="+map.get(key));
}
}
}