Java习惯用法总结

2016/3/2 posted in  Java

实现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() { ... }
}
  • foo.equals(null)必须返回falsenull instanceof 任意类总是返回false
  • 覆盖equals()时,记得要相应地覆盖hashCode()

实现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) { ... }
}
  • 使用Arrays.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

实现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类负责创建新的对象
  • 基本类型域都可以正确地复制了。同样,我们不需要去克隆StringBigInteger等不可变类型

反转字符串

String reverse(String s) {
  return new StringBuilder(s).reverse().toString();
}
  • 使用reverse()方法