【Java】HashMap 和 TreeMap

一. HashMap

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

Java Platform SE 7 【Java】HashMap 和 TreeMaphttps://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);
}

上一篇:Java-TreeMap


下一篇:LeetCode——日常刷题(一)