map

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);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值