今天讲了一次set和map的讨论班,由于自己准备的不好,遇到了很多的尴尬时刻,但是今天学到的只是2还是很多的:
集合
主要集合描述:
Java集合主要有三种重要的类型:
1、List是一个有序集合,可以重复放入数据
2、Set是一个无序集合,不允许重新放入数据
3、Map是一个无序集合,集合中包括一个键对象,一个值对象,键对象不允许重复,值对象可以重复(以键值对的方式存在)
List
1、ArrayList 底层采用的是数组存储元素,适合查询,不适合频繁随机的增删元素
2、LinkedList底层采用双向链表这种数据结构的存储,链表适合频繁的增删元素,不适合查询操作。
3、Vector底层是和ArrayList集合相同,但是Vector是线程安全的。效率较低,所以现在很少使用。
Set
1、HashSet哈希表/散列表。
(1)哈希表:数组与单向链表的结合,哈希表本质是一个数组,只不过这个数组中的每一个元素又是单向链表,其实上哈希表类似于现实世界中的字典;
这里面HashSet的底层是HashMap,而HashMap底层是哈希表,哈希表的 本质是一个数组,但是每一个元素又是一个单项链表,但是HashSet和 HashMap 的哈希表又是有一点细节上的差异的,例如Map是 以键值对的形式存在的,而Set不是这样的,那么HashSet的底层又怎么是HashMap呢,这下我们就去他们的工具类中去寻找一下答案。
{
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
/**
* Constructs a new, empty set; the backing HashMap instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
}
这里面指出在HashSet中,存入的那个值是 作为HashMap中的键存在的,后面是new了 一个Object对象(空) ,
HashSet的add方法是调用了 Map中的put方法,但是这个add方法是Boolean型的,这就有 出现的新的问题,这个bool函数是如何实现的:
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这是put的一个实现 ,
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
这是putVal的实现,那么联系上文的那个bool型的add方法,来解读 这个函数:
(我的理解是这样的)
1、浅显的看,根据自己写代码的经验,最后函数正确执行到最后,返回的是null,没有执行到最后返回的是oldValue,那么这样来讲我们的add函数就可以解释的通了,很完美,我们就剩这个函数按照自己内心的那个轨迹解释一下,这个问题,就完全跑通了;
2、这段代码的大致意思就是如果以前的这个key值,就 返回oldvalue,并且添加失败,(上文讲了,set是无序不可重复的,并且HashSet中获取的值 是HashMap中的key ),于是这个问题就大致解释通了,要想进一步了解,就多看一些sun公司的Java源码;
第二个遇到的大的问题就是关于equals和 hashcode的:
我写的测试代码如下:
package set;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Taoyongpan on 2017/4/6.
* hashcode和equals方法
* HashMap中有一个put方法,put(key,value)key是无序不可重复的
*/
public class SetTest2 {
public static void main(String[] args)
{
//创建集合
Set es = new HashSet();
Employee e1 = new Employee("1000","tao");
Employee e2 = new Employee("1000","tao");
// Employee e2 = new Employee("1001","tao1");
Employee e3 = new Employee("1002","tao2");
Employee e4 = new Employee("1003","tao3");
Employee e5 = new Employee("1004","tao4");
Employee e6 = new Employee("1005","tao5");
// System.out.println(e1.equals(e2));
// System.out.println(e2);
System.out.println(e1.hashCode());
System.out.println(e2.hashCode());
es.add(e1);
es.add(e2);
es.add(e3);
es.add(e4);
es.add(e5);
es.add(e6);
System.out.println(es.size());
}
}
class Employee{
String num;//员工编号
String name;
Employee(String num,String name){
this.num = num;
this.name = name;
}
//重写equals方法,如果员工编号相同并且名字相同,则是同一个对象
public boolean equals(Object o){
System.out.println("调用equals");
if (this == o){
return true;
}
if (o instanceof Employee){
Employee e = (Employee) o;
if (e.num.equals(this.num) && e.name.equals(this.name))
{
return true;
}
}
return false;
}
//重写Hashcode方法
public int hashCode(){
System.out.println("调用hash");
//以员工编号分组,可散列均匀分布
return num.hashCode();
}
}
这个里面e1和e2的问题:他们什么情况下是一个员工,什么情况下当做两个员工;
首先我们了解一些知识:一切对象 都是有HashCode的;为了快速的验证两个对象是否相等。如果两个对象的hashcode不等,这两个对象就不等,如果hashcode相等,再进一步比较equals方法。这样有什么好处呢?因为hashcode是int,比较它们是否相等速度非常快,可以提高性能。
HashCode
然后讲下什么是HashCode,总结几个关键点:
1、HashCode的存在主要是为了查找的快捷性,HashCode是用来在散列存储结构中确定对象的存储地址的
2、如果两个对象equals相等,那么这两个对象的HashCode一定也相同
3、如果对象的equals方法被重写,那么对象的HashCode方法也尽量重写
4、如果两个对象的HashCode相同,不代表两个对象就相同,只能说明这两个对象在散列存储结构中,存放于同一个位置
这时候有的人就会跳出来一些疑问,String类型的可以直接使用equals()方法进行比较呢,这时候我们就要去 String的工具类一探究竟:
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
*
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
*
* using {@code int} arithmetic, where {@code s[i]} is the
* ith character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
上面这段代码是String工具类里面的一段代码,这件事告诉了我们String类型的对象hashcode的重写sun公司已经帮助你写过了,那么其他的呢,他们不帮助你当然是你你自己写了,你要是心情比较好可以自己开发一个工具类,这样就不用自己手写了;
然后我们需要着重记住的是两个对象比较先调用的是HashCode的比较,然后才是equals()方法,原因上文中有;
今天总结的大概就这样了。以后再接再厉。