Java习惯用法(上)

来源:互联网 发布:申请域名知乎 编辑:程序博客网 时间:2024/06/14 02:44

参考自:ImportNew

实现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() 保持一致。

实现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 必定成立。
  • 你不需要保证,当x.equals(y) == false时,x.hashCode() != y.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()的实现与这个类似。

实现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)包装它。

使用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的所有方法都是同步的,可以在多线程环境中使用,而你通常不需要同步的方。

生成一个范围内的随机整数

Random rand = new Random(); // Between 1 and 6, inclusiveint diceRoll() {  return rand.nextInt(6) + 1;}
  • 总是使用Java API方法去生成一个整数范围内的随机数。
  • 不要试图去使用 Math.abs(rand.nextInt()) % n 这些不确定的用法,因为它的结果是有偏差的。此外,它的结果值有可能是负数,比如当rand.nextInt() == Integer.MIN_VALUE时就会如此。

使用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()方法。

返转字符串

String reverse(String s) {  return new StringBuilder(s).reverse().toString();}

启动一条线程

实现Runnnable的方式:

void startAThread0() {  new Thread(new MyRunnable()).start();} class MyRunnable implements Runnable {  public void run() {    ...  }}
继承Thread的方式:
void startAThread1() {  new MyThread().start();} class MyThread extends Thread {  public void run() {    ...  }}
匿名继承Thread的方式:

void startAThread2() {  new Thread() {    public void run() {      ...    }  }.start();}

  • 不要直接调用run()方法。总是调用Thread.start()方法,这个方法会创建一条新的线程并使新建的线程调用run()。

使用try-finally

I/O流例子:
void writeStuff() throws IOException {  OutputStream out = new FileOutputStream(...);  try {    out.write(...);  } finally {    out.close();  }}
锁例子:
void doWithLock(Lock lock) {  lock.acquire();  try {    ...  } finally {    lock.release();  }}
  • 如果try之前的语句运行失败并且抛出异常,那么finally语句块就不会执行。但无论怎样,在这个例子里不用担心资源的释放。
  • 如果try语句块里面的语句抛出异常,那么程序的运行就会跳到finally语句块里执行尽可能多的语句,然后跳出这个方法(除非这个方法还有另一个外围的finally语句块)。

从输入流里读取字节数据

InputStream in = (...);try {  while (true) {    int b = in.read();    if (b == -1)      break;    (... process b ...)  }} finally {  in.close();}
  • read()方法要么返回下一次从流里读取的字节数(0到255,包括0和255),要么在达到流的末端时返回-1。
  • 参考:java.io.InputStream.read()。

从输入流里读取块数据

InputStream in = (...);try {  byte[] buf = new byte[100];  while (true) {    int n = in.read(buf);    if (n == -1)      break;    (... process buf with offset=0 and length=n ...)  }} finally {  in.close();}
  • 要记住的是,read()方法不一定会填满整个buf,所以你必须在处理逻辑中考虑返回的长度。
  • 参考: java.io.InputStream.read(byte[])、java.io.InputStream.read(byte[], int, int)。

从文件里读取文本

BufferedReader in = new BufferedReader(    new InputStreamReader(new FileInputStream(...), "UTF-8"));try {  while (true) {    String line = in.readLine();    if (line == null)      break;    (... process line ...)  }} finally {  in.close();}
  • BufferedReader对象的创建显得很冗长。这是因为Java把字节和字符当成两个不同的概念来看待(这与C语言不同)。
  • 你可以使用任何类型的InputStream来代替FileInputStream,比如socket。
  • 当达到流的末端时,BufferedReader.readLine()会返回null。
  • 要一次读取一个字符,使用Reader.read()方法。
  • 你可以使用其他的字符编码而不使用UTF-8,但最好不要这样做。
  • 参考:java.io.BufferedReader、java.io.InputStreamReader。

向文件里写文本

PrintWriter out = new PrintWriter(    new OutputStreamWriter(new FileOutputStream(...), "UTF-8"));try {  out.print("Hello ");  out.print(42);  out.println(" world!");} finally {  out.close();}
  • Printwriter对象的创建显得很冗长。这是因为Java把字节和字符当成两个不同的概念来看待(这与C语言不同)。
  • 就像System.out,你可以使用print()和println()打印多种类型的值。
  • 你可以使用其他的字符编码而不使用UTF-8,但最好不要这样做。
  • 参考:java.io.PrintWriter、java.io.OutputStreamWriter。

预防性检测(Defensive checking)数值

int factorial(int n) {  if (n < 0)    throw new IllegalArgumentException("Undefined");  else if (n >= 13)    throw new ArithmeticException("Result overflow");  else if (n == 0)    return 1;  else    return n * factorial(n - 1);}
  • 不要认为输入的数值都是正数、足够小的数等等。要显式地检测这些条件。
  • 一个设计良好的函数应该对所有可能性的输入值都能够正确地执行。要确保所有的情况都考虑到了并且不会产生错误的输出(比如溢出)

预防性检测对象

int findIndex(List<String> list, String target) {  if (list == null || target == null)    throw new NullPointerException();  ...}

预防性检测数组索引

void frob(byte[] b, int index) {  if (b == null)    throw new NullPointerException();  if (index < 0 || index >= b.length)    throw new IndexOutOfBoundsException();  ...}

预防性检测数组区间

void frob(byte[] b, int off, int len) {  if (b == null)    throw new NullPointerException();  if (off < 0 || off > b.length    || len < 0 || b.length - off < len)    throw new IndexOutOfBoundsException();  ...}

填充数组元素

// Fill each element of array 'a' with 123byte[] a = (...);for (int i = 0; i < a.length; i++)  a[i] = 123;

(优先)使用标准库的方法:

Arrays.fill(a, (byte)123);

复制一个范围内的数组元素

// Copy 8 elements from array 'a' starting at offset 3// to array 'b' starting at offset 6,// assuming 'a' and 'b' are distinct arraysbyte[] a = (...);byte[] b = (...);for (int i = 0; i < 8; i++)  b[6 + i] = a[3 + i];

(优先)使用标准库的方法:

System.arraycopy(a, 3, b, 6, 8);
  • 参考:java.lang.System.arraycopy(Object, int, Object, int, int)。








0 0
原创粉丝点击