import java.util.HashMap;
class Person
{
int id;
String name;
public Person(int id, String name) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
}
public String toString()
{
return "id: "+id+" name: "+name;
}
public int hashCode()
{
return this.id;
}
public boolean equals(Object obj)
{
Person p = (Person)obj;
return this.id==p.id;
}
}
public class Demo1 {
public static void main(String[] args) {
HashMap<Person, String>map = new HashMap<Person, String>();
//首先会调用键的hashcode得到哈希值,然后经过运算可以算出该元素在哈希表中的存储位置
map.put(new Person(110, "狗娃"),"001");
map.put(new Person(112, "铁蛋"),"001");
map.put(new Person(110, "狗娃"),"002");//如果出现了相同的键,后添加的值会取代之前的值
System.out.println(map);
}
}
import java.util.TreeMap;
//TreeMap是基于红黑树实现的,如果键具备自然顺序,那么就会对键的自然顺序进行排序存储
class Emp implements Comparable<Emp>
{
String name;
int salary;
public Emp(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String toString()
{
return "name: "+ name+ " salary: "+salary;
}
public int compareTo(Emp o)//往TreeMap中添加元素的时候,如果元素的键不具备自然顺序属性,那么键所属的类
//就必须要实现Comparable接口,比较的规则定义在CompareTo方法上
{
return this.salary - o.salary;
}
}
//class MyComparator implements Comparable<Emp>
//{
// public int compare(Emp o1,Emp o2)
// {
// return o1.salary - o2.salary;
// }
//}
public class TreeMap1 {
public static void main(String[] args) {
/*TreeMap <Character,Integer> tree = new TreeMap<Character, Integer>();
tree.put('a',65);
tree.put('b',66);
tree.put('c',67);
System.out.println(tree);//根据键来排序的*/
//
//MyComparator comparator = new MyComparator(comparator);
TreeMap<Emp,String> tree = new TreeMap<Emp, String>();
tree.put(new Emp("狗娃",3005),"01");
//tree.put(new Person1("狗剩",9895),"02");
tree.put(new Emp("张三",5),"03");
tree.put(new Emp("张三",3),"04");
System.out.println(tree);
}
}