JAVAJava开发那些事程序员

读《阿里巴巴Java开发手册》的一点思考

2017-03-15  本文已影响584人  实例波

1.前言

最近在上下班的地铁上把《阿里巴巴Java开发手册》读了一遍,感觉获益匪浅。读的过程中也有一些思考和疑惑,就抽时间亲自尝试了一下。下面用这篇文章把我的问题和答案整理出来。

2.正文

  1. 手册里提到,如果重写equals()方法,就必须重写hashCode()方法,网上查了一下如何重写hashCode(),发现好多重写方法里都出现了31这个神奇的数字。以下是String类的hashCode()实现:
@Override public int hashCode() {
        int hash = hashCode;
        if (hash == 0) {
            if (count == 0) {
                return 0;
            }
            for (int i = 0; i < count; ++i) {
                hash = 31 * hash + charAt(i);
            }
            hashCode = hash;
        }
        return hash;
    }

这个magic number勾起了我的兴趣,重写hashCode()方法为什么会不约而同地用到31这个数字呢?
在网上查了一下,这个问题也没有标准的答案,以下是我查找到的一些比较令人信服的答案:

比较权威的答案是Stack OverFlow上:
According to Joshua Bloch's『Effective Java』:
The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting.
The advantage of using a prime is less clear, but it is traditional.
A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i.
Modern VMs do this sort of optimization automatically.

翻译:
根据 Joshua Bloch 的著作『Effective Java』:
设计者选择 31 这个值是因为它是一个奇质数。如果它是一个偶数,在使用乘法当中产生数值溢出时,原有数字的信息将会丢失,因为乘以二相当于位移。
选择质数的优势不是那么清晰,但是这是一个传统。
31 的一个优良的性质是:乘法可以被位移和减法替代: 31 * i == (i << 5) - i
现代的 VM 可以自行完成这个优化。

  1. 手册里还留下了一个问题:
List<String> a = new ArrayList<String>();
        a.add("1");
        a.add("2");
        for (String temp : a) {
            if ("1".equals(temp)) {
                a.remove(temp);
            }
        }

这段代码执行时不会抛出异常,但是如果将equals前面的"1"换成"2"就会抛出ConcurrentModificationException,使用Iterator来进行删除操作也不会抛出异常,这是为什么呢?

通过分析源码发现,在Iterator的remove()和next()方法中都调用了checkForComodification()方法:

final void checkForComodification() {
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    }

就是在这里抛出了ConcurrentModificationException.

modCount:修改次数
expectedModCount:预期的修改次数

使用ArrayList的remove(),只会使modCount++,不会修改expectedModCount
使用Iterator的remove(),则是expectedModCount = ++modCount

前面提到remove("1")时不会抛出异常,这是因为foreach方法其实也是调用了Iterator的hasNext()和next(),next()里调了checkForComodification(),hasNext()却没调用,remove("1")后,hasNext()返回false,就不会走到next(),所以也就不会抛出异常了,这其实只是一个巧合。
所以:不要在foreach循环里进行元素的remove/add操作,remove元素请使用Iterator方式,如果并发操作,需要对Iterator对象加锁。
具体的分析过程可以参考:http://blog.csdn.net/qq_28816195/article/details/78433544

3.结语

参加工作后才发现,代码规范其实是极其重要的,优雅的代码便于理解和维护,更加节省时间。就像通过一个人的字就能大概看出这是一个什么样的人,代码亦是如此。刚毕业不久的我,更应该培养好的代码规范,这对今后的成长必然是大有益处的。

上一篇 下一篇

猜你喜欢

热点阅读