文章标题

来源:互联网 发布:淘宝黑莓 编辑:程序博客网 时间:2024/05/24 07:45
转载: 学Java必看:Java最常用方法总结(ImportNew年度好文)

目录(?)[+]

  1. 目录
  2. 实现equals
  3. 实现hashCode
  4. 实现compareTo
  5. 实现clone
  6. 使用StringBuilder或StringBuffer
  7. 生成一个范围内的随机整数
  8. 使用Iteratorremove
  9. 返转字符串
  10. 启动一条线程
  11. 使用try-finally
  12. 从输入流里读取字节数据
  13. 从输入流里读取块数据
  14. 从文件里读取文本
  15. 向文件里写文本
  16. 预防性检测Defensive checking数值
  17. 预防性检测对象
  18. 预防性检测数组索引
  19. 预防性检测数组区间
  20. 填充数组元素
  21. 复制一个范围内的数组元素
  22. 调整数组大小
  23. 把4个字节包装packing成一个int
  24. 把int分解Unpacking成4个字节

在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()

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. class Person {  
  2.   String name;  
  3.   int birthYear;  
  4.   byte[] raw;  
  5.    
  6.   public boolean equals(Object obj) {  
  7.     if(!obj instanceofPerson)  
  8.       return false;  
  9.    
  10.     Person other = (Person)obj;  
  11.     return name.equals(other.name)  
  12.         && birthYear == other.birthYear  
  13.         && Arrays.equals(raw, other.raw);  
  14.   }  
  15.    
  16.   public int hashCode() { … }  
  17. }  
class Person {  String name;  int birthYear;  byte[] raw;  public boolean equals(Object obj) {    if(!obj instanceofPerson)      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()

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. class Person {  
  2.   String a;  
  3.   Object b;  
  4.   bytec;  
  5.   int[] d;  
  6.    
  7.   public int hashCode() {  
  8.     return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d);  
  9.   }  
  10.    
  11.   public boolean equals(Object o) { … }  
  12. }  
class Person {  String a;  Object b;  bytec;  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()。但是,如果你可以尽可能地使它成立的话,这会提高哈希表的性能。
  • hashCode()最简单的合法实现就是简单地return 0;虽然这个实现是正确的,但是这会导致HashMap这些数据结构运行得很慢。
  • 参考:java.lang.Object.hashCode()。

实现compareTo()

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. class Person implementsComparable<Person> {  
  2.   String firstName;  
  3.   String lastName;  
  4.   intbirthdate;  
  5.    
  6.   // Compare by firstName, break ties by lastName, finally break ties by birthdate  
  7.   public int compareTo(Person other) {  
  8.     if(firstName.compareTo(other.firstName) != 0)  
  9.       returnfirstName.compareTo(other.firstName);  
  10.     else if (lastName.compareTo(other.lastName) != 0)  
  11.       returnlastName.compareTo(other.lastName);  
  12.     else if (birthdate < other.birthdate)  
  13.       return-1;  
  14.     else if (birthdate > other.birthdate)  
  15.       return1;  
  16.     else  
  17.       return0;  
  18.   }  
  19. }  
class Person implementsComparable<Person> {  String firstName;  String lastName;  intbirthdate;  // Compare by firstName, break ties by lastName, finally break ties by birthdate  public int compareTo(Person other) {    if(firstName.compareTo(other.firstName) != 0)      returnfirstName.compareTo(other.firstName);    else if (lastName.compareTo(other.lastName) != 0)      returnlastName.compareTo(other.lastName);    else if (birthdate < other.birthdate)      return-1;    else if (birthdate > other.birthdate)      return1;    else      return0;  }}

  • 总是实现泛型版本 Comparable 而不是实现原始类型 Comparable 。因为这样可以节省代码量和减少不必要的麻烦。
  • 只关心返回结果的正负号(负/零/正),它们的大小不重要。
  • Comparator.compare()的实现与这个类似。
  • 参考:java.lang.Comparable。

实现clone()

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. class Values implementsCloneable {  
  2.   String abc;  
  3.   doublefoo;  
  4.   int[] bars;  
  5.   Date hired;  
  6.    
  7.   public Values clone() {  
  8.     try{  
  9.       Values result = (Values)super.clone();  
  10.       result.bars = result.bars.clone();  
  11.       result.hired = result.hired.clone();  
  12.       returnresult;  
  13.     }catch(CloneNotSupportedException e) {  // Impossible  
  14.       thrownew AssertionError(e);  
  15.     }  
  16.   }  
  17. }  
class Values implementsCloneable {  String abc;  doublefoo;  int[] bars;  Date hired;  public Values clone() {    try{      Values result = (Values)super.clone();      result.bars = result.bars.clone();      result.hired = result.hired.clone();      returnresult;    }catch(CloneNotSupportedException e) {  // Impossible      thrownew 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

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. // join([“a”, “b”, “c”]) -> “a and b and c”  
  2. String join(List<String> strs) {  
  3.   StringBuilder sb = newStringBuilder();  
  4.   booleanfirst = true;  
  5.   for(String s : strs) {  
  6.     if(first) first = false;  
  7.     elsesb.append(” and ”);  
  8.     sb.append(s);  
  9.   }  
  10.   returnsb.toString();  
  11. }  
// join(["a", "b", "c"]) -> "a and b and c"String join(List<String> strs) {  StringBuilder sb = newStringBuilder();  booleanfirst = true;  for(String s : strs) {    if(first) first = false;    elsesb.append(" and ");    sb.append(s);  }  returnsb.toString();}

  • 不要像这样使用重复的字符串连接:s += item ,因为它的时间效率是O(n^2)。
  • 使用StringBuilder或者StringBuffer时,可以使用append()方法添加文本和使用toString()方法去获取连接起来的整个文本。
  • 优先使用StringBuilder,因为它更快。StringBuffer的所有方法都是同步的,而你通常不需要同步的方法。
  • 参考java.lang.StringBuilder、java.lang.StringBuffer。

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

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. Random rand = newRandom();  
  2.    
  3. // Between 1 and 6, inclusive  
  4. intdiceRoll() {  
  5.   return rand.nextInt(6) + 1;  
  6. }  
Random rand = newRandom();// Between 1 and 6, inclusiveintdiceRoll() {  return rand.nextInt(6) + 1;}

  • 总是使用Java API方法去生成一个整数范围内的随机数。
  • 不要试图去使用 Math.abs(rand.nextInt()) % n 这些不确定的用法,因为它的结果是有偏差的。此外,它的结果值有可能是负数,比如当rand.nextInt() == Integer.MIN_VALUE时就会如此。
  • 参考:java.util.Random.nextInt(int)。

使用Iterator.remove()

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void filter(List<String> list) {  
  2.   for(Iterator<String> iter = list.iterator(); iter.hasNext(); ) {  
  3.     String item = iter.next();  
  4.     if(…)  
  5.       iter.remove();  
  6.   }  
  7. }  
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()。

返转字符串

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. String reverse(String s) {  
  2.   return new StringBuilder(s).reverse().toString();  
  3. }  
String reverse(String s) {  return new StringBuilder(s).reverse().toString();}

  • 这个方法可能应该加入Java标准库。
  • 参考:java.lang.StringBuilder.reverse()。

启动一条线程

下面的三个例子使用了不同的方式完成了同样的事情。

实现Runnnable的方式:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void startAThread0() {  
  2.   new Thread(newMyRunnable()).start();  
  3. }  
  4.    
  5. class MyRunnable implementsRunnable {  
  6.   public void run() {  
  7.     …  
  8.   }  
  9. }  
void startAThread0() {  new Thread(newMyRunnable()).start();}class MyRunnable implementsRunnable {  public void run() {    ...  }}

继承Thread的方式:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void startAThread1() {  
  2.   new MyThread().start();  
  3. }  
  4.    
  5. class MyThread extendsThread {  
  6.   public void run() {  
  7.     …  
  8.   }  
  9. }  
void startAThread1() {  new MyThread().start();}class MyThread extendsThread {  public void run() {    ...  }}

匿名继承Thread的方式:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void startAThread2() {  
  2.   new Thread() {  
  3.     publicvoid run() {  
  4.       …  
  5.     }  
  6.   }.start();  
  7. }  
void startAThread2() {  new Thread() {    publicvoid run() {      ...    }  }.start();}

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

使用try-finally

I/O流例子:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void writeStuff() throwsIOException {  
  2.   OutputStream out = newFileOutputStream(…);  
  3.   try{  
  4.     out.write(…);  
  5.   }finally{  
  6.     out.close();  
  7.   }  
  8. }  
void writeStuff() throwsIOException {  OutputStream out = newFileOutputStream(...);  try{    out.write(...);  }finally{    out.close();  }}

锁例子:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void doWithLock(Lock lock) {  
  2.   lock.acquire();  
  3.   try{  
  4.     …  
  5.   }finally{  
  6.     lock.release();  
  7.   }  
  8. }  
void doWithLock(Lock lock) {  lock.acquire();  try{    ...  }finally{    lock.release();  }}

  • 如果try之前的语句运行失败并且抛出异常,那么finally语句块就不会执行。但无论怎样,在这个例子里不用担心资源的释放。
  • 如果try语句块里面的语句抛出异常,那么程序的运行就会跳到finally语句块里执行尽可能多的语句,然后跳出这个方法(除非这个方法还有另一个外围的finally语句块)。

从输入流里读取字节数据

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. InputStream in = (…);  
  2. try{  
  3.   while(true) {  
  4.     intb = in.read();  
  5.     if(b == -1)  
  6.       break;  
  7.     (… process b …)  
  8.   }  
  9. }finally{  
  10.   in.close();  
  11. }  
InputStream in = (...);try{  while(true) {    intb = in.read();    if(b == -1)      break;    (... process b ...)  }}finally{  in.close();}

  • read()方法要么返回下一次从流里读取的字节数(0到255,包括0和255),要么在达到流的末端时返回-1。
  • 参考:java.io.InputStream.read()。

从输入流里读取块数据

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. InputStream in = (…);  
  2. try{  
  3.   byte[] buf = newbyte[100];  
  4.   while(true) {  
  5.     intn = in.read(buf);  
  6.     if(n == -1)  
  7.       break;  
  8.     (… process buf with offset=0and length=n …)  
  9.   }  
  10. }finally{  
  11.   in.close();  
  12. }  
InputStream in = (...);try{  byte[] buf = newbyte[100];  while(true) {    intn = in.read(buf);    if(n == -1)      break;    (... process buf with offset=0and length=n ...)  }}finally{  in.close();}

  • 要记住的是,read()方法不一定会填满整个buf,所以你必须在处理逻辑中考虑返回的长度。
  • 参考: java.io.InputStream.read(byte[])、java.io.InputStream.read(byte[], int, int)。

从文件里读取文本

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. BufferedReader in = newBufferedReader(  
  2.     newInputStreamReader(newFileInputStream(…), ”UTF-8”));  
  3. try{  
  4.   while(true) {  
  5.     String line = in.readLine();  
  6.     if(line == null)  
  7.       break;  
  8.     (… process line …)  
  9.   }  
  10. }finally{  
  11.   in.close();  
  12. }  
BufferedReader in = newBufferedReader(    newInputStreamReader(newFileInputStream(...), "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。

向文件里写文本

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. PrintWriter out = newPrintWriter(  
  2.     newOutputStreamWriter(newFileOutputStream(…), ”UTF-8”));  
  3. try{  
  4.   out.print(”Hello ”);  
  5.   out.print(42);  
  6.   out.println(” world!”);  
  7. }finally{  
  8.   out.close();  
  9. }  
PrintWriter out = newPrintWriter(    newOutputStreamWriter(newFileOutputStream(...), "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)数值


[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. int factorial(intn) {  
  2.   if(n < 0)  
  3.     thrownew IllegalArgumentException(”Undefined”);  
  4.   else if (n >= 13)  
  5.     thrownew ArithmeticException(”Result overflow”);  
  6.   else if (n == 0)  
  7.     return 1;  
  8.   else  
  9.     return n * factorial(n - 1);  
  10. }  
int factorial(intn) {  if(n < 0)    thrownew IllegalArgumentException("Undefined");  else if (n >= 13)    thrownew ArithmeticException("Result overflow");  else if (n == 0)    return 1;  else    return n * factorial(n - 1);}

  • 不要认为输入的数值都是正数、足够小的数等等。要显式地检测这些条件。
  • 一个设计良好的函数应该对所有可能性的输入值都能够正确地执行。要确保所有的情况都考虑到了并且不会产生错误的输出(比如溢出)。

预防性检测对象

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. int findIndex(List<String> list, String target) {  
  2.   if(list == null|| target == null)  
  3.     throw new NullPointerException();  
  4.   …  
  5. }  
int findIndex(List<String> list, String target) {  if(list == null|| target == null)    throw new NullPointerException();  ...}

  • 不要认为对象参数不会为空(null)。要显式地检测这个条件。

预防性检测数组索引

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void frob(byte[] b, intindex) {  
  2.   if(b == null)  
  3.     throw new NullPointerException();  
  4.   if(index < 0|| index >= b.length)  
  5.     throw new IndexOutOfBoundsException();  
  6.   …  
  7. }  
void frob(byte[] b, intindex) {  if(b == null)    throw new NullPointerException();  if(index < 0|| index >= b.length)    throw new IndexOutOfBoundsException();  ...}
  • 不要认为所以给的数组索引不会越界。要显式地检测它。

预防性检测数组区间

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. void frob(byte[] b, intoff, intlen) {  
  2.   if(b == null)  
  3.     throw new NullPointerException();  
  4.   if(off < 0|| off > b.length  
  5.     || len < 0|| b.length - off < len)  
  6.     throw new IndexOutOfBoundsException();  
  7.   …  
  8. }  
void frob(byte[] b, intoff, intlen) {  if(b == null)    throw new NullPointerException();  if(off < 0|| off > b.length    || len < 0|| b.length - off < len)    throw new IndexOutOfBoundsException();  ...}

  • 不要认为所给的数组区间(比如,从off开始,读取len个元素)是不会越界。要显式地检测它。

填充数组元素

使用循环:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. // Fill each element of array ‘a’ with 123  
  2. byte[] a = (…);  
  3. for(inti = 0; i < a.length; i++)  
  4.   a[i] = 123;  
// Fill each element of array 'a' with 123byte[] a = (...);for(inti = 0; i < a.length; i++)  a[i] = 123;

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

Arrays.fill(a, (byte)123);
  • 参考:java.util.Arrays.fill(T[], T)。
  • 参考:java.util.Arrays.fill(T[], int, int, T)。

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

使用循环:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. // Copy 8 elements from array ‘a’ starting at offset 3  
  2. // to array ‘b’ starting at offset 6,  
  3. // assuming ‘a’ and ‘b’ are distinct arrays  
  4. byte[] a = (…);  
  5. byte[] b = (…);  
  6. for(inti = 0; i < 8; i++)  
  7.   b[6+ i] = a[3+ i];  
// 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(inti = 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)。

调整数组大小

使用循环(扩大规模):

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. // Make array ‘a’ larger to newLen  
  2. byte[] a = (…);  
  3. byte[] b = newbyte[newLen];  
  4. for(int i = 0; i < a.length; i++)  // Goes up to length of A  
  5.   b[i] = a[i];  
  6. a = b;  
// Make array 'a' larger to newLenbyte[] a = (...);byte[] b = newbyte[newLen];for(int i = 0; i < a.length; i++)  // Goes up to length of A  b[i] = a[i];a = b;

使用循环(减小规模):

// Make array 'a' smaller to newLenbyte[] a = (...);byte[] b = new byte[newLen];for (int i = 0; i < b.length; i++)  // Goes up to length of B  b[i] = a[i];a = b;

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




1
a = Arrays.copyOf(a, newLen);



  • 参考:java.util.Arrays.copyOf(T[], int)。
  • 参考:java.util.Arrays.copyOfRange(T[], int, int)。

把4个字节包装(packing)成一个int

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. int packBigEndian(byte[] b) {  
  2.   return (b[0] & 0xFF) << 24  
  3.        | (b[1] & 0xFF) << 16  
  4.        | (b[2] & 0xFF) <<  8  
  5.        | (b[3] & 0xFF) <<  0;  
  6. }  
  7.    
  8. int packLittleEndian(byte[] b) {  
  9.   return (b[0] & 0xFF) <<  0  
  10.        | (b[1] & 0xFF) <<  8  
  11.        | (b[2] & 0xFF) << 16  
  12.        | (b[3] & 0xFF) << 24;  
  13. }  
int packBigEndian(byte[] b) {  return (b[0] & 0xFF) << 24       | (b[1] & 0xFF) << 16       | (b[2] & 0xFF) <<  8       | (b[3] & 0xFF) <<  0;}int packLittleEndian(byte[] b) {  return (b[0] & 0xFF) <<  0       | (b[1] & 0xFF) <<  8       | (b[2] & 0xFF) << 16       | (b[3] & 0xFF) << 24;}


把int分解(Unpacking)成4个字节

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. byte[] unpackBigEndian(intx) {  
  2.   return new byte[] {  
  3.     (byte)(x >>> 24),  
  4.     (byte)(x >>> 16),  
  5.     (byte)(x >>>  8),  
  6.     (byte)(x >>>  0)  
  7.   };  
  8. }  
  9.    
  10. byte[] unpackLittleEndian(intx) {  
  11.   returnnew byte[] {  
  12.     (byte)(x >>>  0),  
  13.     (byte)(x >>>  8),  
  14.     (byte)(x >>> 16),  
  15.     (byte)(x >>> 24)  
  16.   };  
  17. }  
byte[] unpackBigEndian(intx) {  return new byte[] {    (byte)(x >>> 24),    (byte)(x >>> 16),    (byte)(x >>>  8),    (byte)(x >>>  0)  };}byte[] unpackLittleEndian(intx) {  returnnew byte[] {    (byte)(x >>>  0),    (byte)(x >>>  8),    (byte)(x >>> 16),    (byte)(x >>> 24)  };}


  • 总是使用无符号右移操作符(>>>)对位进行包装(packing),不要使用算术右移操作符(>>)。

原文链接: nayuki 翻译: ImportNew.com 进林

译文链接: http://www.importnew.com/15605.html

转载请保留原文出处、译者和译文链接。]

document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000) var fromjs = ("#fromjs");
    if (fromjs.length > 0) {
("#fromjs .markdown_views pre").addClass("prettyprint"); prettyPrint(); ('pre.prettyprint code').each(function () {
                var lines =
(this).text().split('\n').length; var numbering=('
    ').addClass('pre-numbering').hide(); (this).addClass(hasnumbering).parent().append(numbering); for (i = 1; i
0 0
原创粉丝点击