你不需要保证,当x.equals(y)==false时,x.hashCode()!=y.hashCode()。但是,如果你可以尽可能地使它成立的话,这会提高哈希表的性能。
  hashCode()简单的合法实现是简单地return 0;虽然这个实现是正确的,但是这会导致HashMap这些数据结构运行得很慢。
  参考:java.lang.Object.hashCode()。
  实现compareTo()
  class Person implements Comparable<Person>{
  String firstName;
  String lastName;
  int birthdate;
  //Compare by firstName,break ties by lastName,finally break ties by birthdate
  public int compareTo(Person other){
  if(firstName.compareTo(other.firstName)!=0)
  return firstName.compareTo(other.firstName);
  else if(lastName.compareTo(other.lastName)!=0)
  return lastName.compareTo(other.lastName);
  else if(birthdate<other.birthdate)
  return-1;
  else if(birthdate>other.birthdate)
  return 1;
  else
  return 0;
  }
  }
  总是实现泛型版本Comparable而不是实现原始类型Comparable。因为这样可以节省代码量和减少不必要的麻烦。
  只关心返回结果的正负号(负/零/正),它们的大小不重要。
  Comparator.compare()的实现与这个类似。
  参考:java.lang.Comparable。
  实现clone()
  class Values implements Cloneable{
  String abc;
  double foo;
  int[]bars;
  Date hired;
  public Values clone(){
  try{
  Values result=(Values)super.clone();
  result.bars=result.bars.clone();
  result.hired=result.hired.clone();
  return result;
  }catch(CloneNotSupportedException e){//Impossible
  throw new AssertionError(e);
  }
  }
  }
  使用super.clone()让Object类负责创建新的对象。
  基本类型域都已经被正确地复制了。同样,我们不需要去克隆String和BigInteger等不可变类型。
  手动对所有的非基本类型域(对象和数组)进行深度复制(deep copy)。
  实现了Cloneable的类,clone()方法永远不要抛CloneNotSupportedException。因此,需要捕获这个异常并忽略它,或者使用不受检异常(unchecked exception)包装它。
  不使用Object.clone()方法而是手动地实现clone()方法是可以的也是合法的。
  参考:java.lang.Object.clone()、java.lang.Cloneable()。
  使用StringBuilder或StringBuffer
  //join(["a","b","c"])->"a and b and c"
  String join(List<String>strs){
  StringBuilder sb=new StringBuilder();
  boolean first=true;
  for(String s:strs){
  if(first)first=false;
  else sb.append("and");
  sb.append(s);
  }
  return sb.toString();
  }
  不要像这样使用重复的字符串连接:s+=item,因为它的时间效率是O(n^2)。
  使用StringBuilder或者StringBuffer时,可以使用append()方法添加文本和使用toString()方法去获取连接起来的整个文本。
  优先使用StringBuilder,因为它更快。StringBuffer的所有方法都是同步的,而你通常不需要同步的方法。
  参考java.lang.StringBuilder、java.lang.StringBuffer。
  生成一个范围内的随机整数
  Random rand=new Random();
  //Between 1 and 6,inclusive
  int diceRoll(){
  return rand.nextInt(6)+1;
  }
  总是使用Java API方法去生成一个整数范围内的随机数。
  不要试图去使用Math.abs(rand.nextInt())%n这些不确定的用法,因为它的结果是有偏差的。此外,它的结果值有可能是负数,比如当rand.nextInt()==Integer.MIN_VALUE时会如此。
  参考:java.util.Random.nextInt(int)。
  使用Iterator.remove()
  void filter(List<String>list){
  for(Iterator<String>iter=list.iterator();iter.hasNext();){
  String item=iter.next();
  if(...)
  iter.remove();
  }
  }
  remove()方法作用在next()方法近返回的条目上。每个条目只能使用一次remove()方法。
  参考:java.util.Iterator.remove()。
  返转字符串
  String reverse(String s){
  return new StringBuilder(s).reverse().toString();
  }
  这个方法可能应该加入Java标准库。
  参考:java.lang.StringBuilder.reverse()。