参考链接:https://blog.csdn.net/pingnanlee/article/details/17228579
参考链接:http://www.tiantianbianma.com/java-hashmap-treemap-hashtable-linkedhashmap.html/
1. HashMap
HashMap底层是基于哈希表实现的,而哈希表对于键值有约束。当使用自定义的类型来做HashMap的键时,为了程序的运行结果正确,必须定义该类型的equals()方法和hashCode()方法。
案例一
HashMap<Dog, Integer> dogMap = new HashMap<Dog, Integer>();
dogMap.put(new Dog("red"), 10);
dogMap.put(new Dog("black"), 15);
dogMap.put(new Dog("white"), 5);
dogMap.put(new Dog("white"), 20);
// 输出结果
4
white dog - 5
black dog -15
red dog - 10
white dog - 20
如果想要完成white同名称的key只存储一次;
必须重写equals()方法和hashCode();
总结:执行顺序如下
1. 先执行hashCode(),获取返回值; 返回值已经存在,则继续判断equals(); 如果hashCode()返回值不存在,则直接可以添加,进而提升了效率;
2. 如果执行equals()方法,返回true则为存在,返回false则为不存在;
贴出一段标准示例代码:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((number == null) ? 0 : number.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;
}
Person p = (Person)obj;
if (name == null) {
if(p.name != null) {
return false;
}
} else if (!name.equals(p.name)) {
return false;
}
if (address == null) {
if (p.address != null) {
return false;
}
} else if (!address.equals(p.address)) {
return false;
}
if (number == null) {
if (p.number != null) {
return false;
}
} else if (!number.equals(p.number)) {
return false;
}
return true;
}
2. TreeMap的元素顺序
TreeMap可以排序元素,TreeMap的底层实现是红黑树;如果对自定义对象进行排序,则必须实现java.util.Comparable接口,重写compareTo()方法;
示例:
class Dog implements Comparable {
String color;
int size;
Dog(String color, int size) {
this.color = color;
this.size = size;
}
@Override
public int compareTo(Dog o) {
return o.size - this.size;
}
}
public class Main {
public static void main(String[] args) {
TreeMap<Dog, Integer> dogMap = new TreeMap<Dog, Integer>();
dogMap.put(new Dog("red", 20), 5);
dogMap.put(new Dog("black", 30), 10);
dogMap.put(new Dog("white", 10), 15);
dogMap.put(new Dog("white", 10), 20);
for (Entry<Dog, Integer> :dogMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}
3. Hashtable
Hashtable与HashMap的区别仅仅是:
1. HashTable是同步的(synchronized)。
2. 不允许有 null 值
4. LinkedHashMap
LinkedHashMap是HashMap的子类,所以通过继承机制,拥有了HashMap的所有特性。而且,它还增加了保持元素插入顺序的特性。
|