注:上述hashCode()的重写中出现了result*31,是因为result*31 = (result<<5) - result。之所以选择31,是因为左移运算和减运算计算效率远大于乘法运算。当然,也可以选择其他数字。
  7.public String toString();
  toString()方法返回该对象的字符串表示。先看一下Object中的具体方法体:
  1 public String toString() {
  2    return getClass().getName() + "@" + Integer.toHexString(hashCode());
  3 }
  toString()方法相信大家都经常用到,即使没有显式调用,但当我们使用System.out.println(obj)时,其内部也是通过toString()来实现的。
  getClass()返回对象的类对象,getClassName()以String形式返回类对象的名称(含包名)。Integer.toHexString(hashCode())则是以对象的哈希码为实参,以16进制无符号整数形式返回此哈希码的字符串表示形式。
  如上例中的u1的哈希码是638,则对应的16进制为27e,调用toString()方法返回的结果为:com.corn.objectsummary.User@27e。
  因此:toString()是由对象的类型和其哈希码确定,同一类型但不相等的两个对象分别调用toString()方法返回的结果可能相同。
  8/9/10/11/12. wait(...) / notify() / notifyAll()
  一说到wait(...) / notify() | notifyAll()几个方法,首先想到的是线程。确实,这几个方法主要用于java多线程之间的协作。先具体看下这几个方法的主要含义:
  wait():调用此方法所在的当前线程等待,直到在其他线程上调用此方法的主调(某一对象)的notify()/notifyAll()方法。
  wait(long timeout)/wait(long timeout, int nanos):调用此方法所在的当前线程等待,直到在其他线程上调用此方法的主调(某一对象)的notisfy()/notisfyAll()方法,或超过指定的超时时间量。
  notify()/notifyAll():唤醒在此对象监视器上等待的单个线程/所有线程。
  wait(...) / notify() | notifyAll()一般情况下都是配套使用。下面来看一个简单的例子:

 

1 package com.qqyumidi;
2
3 public class ThreadTest {
4
5     /**
6      * @param args
7      */
8     public static void main(String[] args) {
9         // TODO Auto-generated method stub
10         MyRunnable r = new MyRunnable();
11         Thread t = new Thread(r);
12         t.start();
13         synchronized (r) {
14             try {
15                 System.out.println("main thread 等待t线程执行完");
16                 r.wait();
17                 System.out.println("被notity唤醒,得以继续执行");
18             } catch (InterruptedException e) {
19                 // TODO Auto-generated catch block
20                 e.printStackTrace();
21                 System.out.println("main thread 本想等待,但被意外打断了");
22             }
23             System.out.println("线程t执行相加结果" + r.getTotal());
24         }
25     }
26 }
27
28 class MyRunnable implements Runnable {
29     private int total;
30
31     @Override
32     public void run() {
33         // TODO Auto-generated method stub
34         synchronized (this) {
35             System.out.println("Thread name is:" + Thread.currentThread().getName());
36             for (int i = 0; i < 10; i++) {
37                 total += i;
38             }
39             notify();
40             System.out.println("执行notif后同步代码块中依然可以继续执行直至完毕");
41         }
42         System.out.println("执行notif后且同步代码块外的代码执行时机取决于线程调度");
43     }
44
45     public int getTotal() {
46         return total;
47     }
48 }