【Java】HashMap 和 TreeMap

一. HashMap

1. HashMap 由键值对组成,key是不能重复的,value 可以重复,通过 key 可以获得 value 值。

Java Platform SE 7 icon-default.png?t=LA92https://docs.oracle.com/javase/7/docs/api/2. HashMap 使用示例

// 定义 HashMap
HashMap<String,String> hs = new HashMap<String,String>();
// put
hs.put("1", "one");
hs.put("2", "two");
hs.put("3", "three");
hs.put("3", "three1");
hs.put("4", "one");
		
// remove
hs.remove("1");	

// 是否包含某个key contains
boolean b = hs.containsKey("2");
System.out.println(b);
		
// 遍历
// 先得到 key 的 set
Set<String> keys = hs.keySet();
// 遍历 key 的 set 得到 value
for(String key: keys){
	String value = hs.get(key);
	System.out.println(key+":"+value);
}

// 自定义的 key 类型,需要重载 hashCode() 和 equals()
class MyInt{

	@Override
	public String toString() {
		return i+"";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + i;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MyInt other = (MyInt) obj;
		if (i != other.i)
			return false;
		return true;
	}

    private int i;
	public MyInt(int i){
		this.i = i;
	}
}

HashMap<MyInt,String> hm = new HashMap<MyInt,String>();
MyInt i1 = new MyInt(1);
MyInt i2 = new MyInt(2);
MyInt i3 = new MyInt(2);

hm.put(i1, "one");
hm.put(i2, "two");
hm.put(i3, "three");
		
for(MyInt key:hm.keySet()){
	String value = hm.get(key);
	System.out.println(key+":"+value);
}

二.  TreeMap

1. TreeMap 中的元素会按照 key 来排序。自定义的 key 对象需要重载 hashCode, equals 和 compareTo 方法。

class MyInt implements Comparable<MyInt>{

	@Override
	public String toString() {
		return i+"";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + i;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MyInt other = (MyInt) obj;
		if (i != other.i)
			return false;
		return true;
	}

	private int i;
	public MyInt(int i){
		this.i = i;
	}

	@Override
	public int compareTo(MyInt o) {
		if(this.i>o.i){
			return -1;
		}else if(this.i<o.i){
			return 1;
		}else{
			return 0;
		}
	}
}

TreeMap<MyInt,String> tm = new TreeMap<MyInt,String>();
MyInt i1 = new MyInt(1);
MyInt i2 = new MyInt(2);
MyInt i3 = new MyInt(3);
		
tm.put(i1, "one");
tm.put(i2, "two");
tm.put(i3, "three");
		
for(MyInt key:tm.keySet()){
	String value = tm.get(key);
	System.out.println(key+":"+value);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值