在Java编程中,有些知识并不能仅通过语言规范或者标准API文档能学到的。在本文中,我会尽量收集一些常用的习惯用法,特别是很难猜到的用法。(Joshua Bloch的《Effective Java》对这个话题给出了更详尽的论述,可以从这本书里学习更多的用法。)
  我把本文的所有代码都放在公共场所里。你可以根据自己的喜好去复制和修改任意的代码片段,不需要任何的凭证。
  目录
  实现:
  equals()
  hashCode()
  compareTo()
  clone()
  应用:
  StringBuilder/StringBuffer
  Random.nextInt(int)
  Iterator.remove()
  StringBuilder.reverse()
  Thread/Runnable
  try-finally
  输入/输出:
  从输入流里读取字节数据
  从输入流里读取块数据
  从文件里读取文本
  向文件里写文本
  预防性检测:
  数值
  对象
  数组索引
  数组区间
  数组:
  填充元素
  复制一个范围内的数组元素
  调整数组大小
  包装:
  个字节包装成一个int
  分解成4个字节
  实现equals()
  class Person{
  String name;
  int birthYear;
  byte[]raw;
  public boolean equals(Object obj){
  if(!obj instanceof Person)
  return false;
  Person other=(Person)obj;
  return name.equals(other.name)
  &&birthYear==other.birthYear
  &&Arrays.equals(raw,other.raw);
  }
  public int hashCode(){...}
  }
  参数必须是Object类型,不能是外围类。
  foo.equals(null)必须返回false,不能抛NullPointerException。(注意,null instanceof任意类总是返回false,因此上面的代码可以运行。)
  基本类型域(比如,int)的比较使用==,基本类型数组域的比较使用Arrays.equals()。
  覆盖equals()时,记得要相应地覆盖hashCode(),与equals()保持一致。
  参考:java.lang.Object.equals(Object)。
  实现hashCode()
  class Person{
  String a;
  Object b;
  byte c;
  int[]d;
  public int hashCode(){
  return a.hashCode()+b.hashCode()+c+Arrays.hashCode(d);
  }
  public boolean equals(Object o){...}
  }
  当x和y两个对象具有x.equals(y)==true,你必须要确保x.hashCode()==y.hashCode()。
  根据逆反命题,如果x.hashCode()!=y.hashCode(),那么x.equals(y)==false必定成立。