13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

关于Java一些习惯用法的总结

在Java编程中,有些知识 并不能仅通过语言规范或者标准API文档就能学到的。在本文中,我会尽量收集一些最常用的习惯用法,特别是很难猜到的用法。(Joshua Bloch的《Effective Java》对这个话题给出了更详尽的论述,可以从这本书里学习更多的用法。)

创新互联公司是专业的文圣网站建设公司,文圣接单;提供成都做网站、成都网站制作,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行文圣网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

我把本文的所有代码都放在公共场所里。你可以根据自己的喜好去复制和修改任意的代码片段,不需要任何的凭证。

实现equals()

 
 
 
 
  1. class Person { 
  2.   String name; 
  3.   int birthYear; 
  4.   byte[] raw; 
  5.  
  6.   public boolean equals(Object obj) { 
  7.     if (!obj instanceof Person) 
  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. }  

实现hashCode()

 
 
 
 
  1. class Person { 
  2.   String a; 
  3.   Object b; 
  4.   byte c; 
  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. }  

实现compareTo()

 
 
 
 
  1. class Person implements Comparable { 
  2.   String firstName; 
  3.   String lastName; 
  4.   int birthdate; 
  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.       return firstName.compareTo(other.firstName); 
  10.     else if (lastName.compareTo(other.lastName) != 0) 
  11.       return lastName.compareTo(other.lastName); 
  12.     else if (birthdate < other.birthdate) 
  13.       return -1; 
  14.     else if (birthdate > other.birthdate) 
  15.       return 1; 
  16.     else 
  17.       return 0; 
  18.   } 
  19. }  

实现clone()

 
 
 
 
  1. class Values implements Cloneable { 
  2.   String abc; 
  3.   double foo; 
  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.       return result; 
  13.     } catch (CloneNotSupportedException e) {  // Impossible 
  14.       throw new AssertionError(e); 
  15.     } 
  16.   } 
  17. }  

使用StringBuilder或StringBuffer

 
 
 
 
  1. // join(["a", "b", "c"]) -> "a and b and c" 
  2. String join(List strs) { 
  3.   StringBuilder sb = new StringBuilder(); 
  4.   boolean first = true; 
  5.   for (String s : strs) { 
  6.     if (first) first = false; 
  7.     else sb.append(" and "); 
  8.     sb.append(s); 
  9.   } 
  10.   return sb.toString(); 
  11. }  

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

 
 
 
 
  1. Random rand = new Random(); 
  2.  
  3. // Between 1 and 6, inclusive 
  4. int diceRoll() { 
  5.   return rand.nextInt(6) + 1; 
  6. }  

使用Iterator.remove()

 
 
 
 
  1. void filter(List list) { 
  2.   for (Iterator iter = list.iterator(); iter.hasNext(); ) { 
  3.     String item = iter.next(); 
  4.     if (...) 
  5.       iter.remove(); 
  6.   } 
  7. }  

返转字符串

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

启动一条线程

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

实现Runnnable的方式:

 
 
 
 
  1. void startAThread0() { 
  2.   new Thread(new MyRunnable()).start(); 
  3.  
  4. class MyRunnable implements Runnable { 
  5.   public void run() { 
  6.     ... 
  7.   } 
  8. }  

继承Thread的方式:

 
 
 
 
  1. void startAThread1() { 
  2.   new MyThread().start(); 
  3.  
  4. class MyThread extends Thread { 
  5.   public void run() { 
  6.     ... 
  7.   } 
  8. }  

匿名继承Thread的方式:

 
 
 
 
  1. void startAThread2() { 
  2.   new Thread() { 
  3.     public void run() { 
  4.       ... 
  5.     } 
  6.   }.start(); 
  7. }  

使用try-finally

I/O流例子:

 
 
 
 
  1. void writeStuff() throws IOException { 
  2.   OutputStream out = new FileOutputStream(...); 
  3.   try { 
  4.     out.write(...); 
  5.   } finally { 
  6.     out.close(); 
  7.   } 
  8. }  

锁例子:

 
 
 
 
  1. void doWithLock(Lock lock) { 
  2.   lock.acquire(); 
  3.   try { 
  4.     ... 
  5.   } finally { 
  6.     lock.release(); 
  7.   } 
  8. }  

从输入流里读取字节数据

 
 
 
 
  1. InputStream in = (...); 
  2. try { 
  3.   while (true) { 
  4.     int b = in.read(); 
  5.     if (b == -1) 
  6.       break; 
  7.     (... process b ...) 
  8.   } 
  9. } finally { 
  10.   in.close(); 
  11. }  

从输入流里读取块数据

 
 
 
 
  1. InputStream in = (...); 
  2. try { 
  3.   byte[] buf = new byte[100]; 
  4.   while (true) { 
  5.     int n = in.read(buf); 
  6.     if (n == -1) 
  7.       break; 
  8.     (... process buf with offset=0 and length=n ...) 
  9.   } 
  10. } finally { 
  11.   in.close(); 
  12. }  

从文件里读取文本

 
 
 
 
  1. BufferedReader in = new BufferedReader( 
  2.     new InputStreamReader(new FileInputStream(...), "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. }  

向文件里写文本

 
 
 
 
  1. PrintWriter out = new PrintWriter( 
  2.     new OutputStreamWriter(new FileOutputStream(...), "UTF-8")); 
  3. try { 
  4.   out.print("Hello "); 
  5.   out.print(42); 
  6.   out.println(" world!"); 
  7. } finally { 
  8.   out.close(); 
  9. }  

预防性检测(Defensive checking)数值

 
 
 
 
  1. int factorial(int n) { 
  2.   if (n < 0) 
  3.     throw new IllegalArgumentException("Undefined"); 
  4.   else if (n >= 13) 
  5.     throw new ArithmeticException("Result overflow"); 
  6.   else if (n == 0) 
  7.     return 1; 
  8.   else 
  9.     return n * factorial(n - 1); 
  10. }  

预防性检测对象

 
 
 
 
  1. int findIndex(List list, String target) { 
  2.   if (list == null || target == null) 
  3.     throw new NullPointerException(); 
  4.   ... 
  5. }  

预防性检测数组索引

 
 
 
 
  1. void frob(byte[] b, int index) { 
  2.   if (b == null) 
  3.     throw new NullPointerException(); 
  4.   if (index < 0 || index >= b.length) 
  5.     throw new IndexOutOfBoundsException(); 
  6.   ... 
  7. }  

预防性检测数组区间

 
 
 
 
  1. void frob(byte[] b, int off, int len) { 
  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. }  

填充数组元素

使用循环:

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

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

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

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

使用循环:

 
 
 
 
  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 (int i = 0; i < 8; i++) 
  7.   b[6 + i] = a[3 + i];  

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

 
 
 
 
  1. System.arraycopy(a, 3, b, 6, 8); 

调整数组大小

使用循环(扩大规模):

 
 
 
 
  1. // Make array 'a' larger to newLen 
  2. byte[] a = (...); 
  3. byte[] b = new byte[newLen]; 
  4. for (int i = 0; i < a.length; i++)  // Goes up to length of A 
  5.   b[i] = a[i]; 
  6. a = b;  

使用循环(减小规模):

 
 
 
 
  1. // Make array 'a' smaller to newLen 
  2.  
  3. byte[] a = (...); 
  4.  
  5. byte[] b = new byte[newLen]; 
  6.  
  7. for (int i = 0; i < b.length; i++) // Goes up to length of B 
  8.  
  9. b[i] = a[i]; 
  10.  
  11. a = b;  

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

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

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

 
 
 
 
  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. int packLittleEndian(byte[] b) { 
  8.   return (b[0] & 0xFF) <<  0 
  9.        | (b[1] & 0xFF) <<  8 
  10.        | (b[2] & 0xFF) << 16 
  11.        | (b[3] & 0xFF) << 24; 
  12. }  

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

 
 
 
 
  1. byte[] unpackBigEndian(int x) { 
  2.   return new byte[] { 
  3.     (byte)(x >>> 24), 
  4.     (byte)(x >>> 16), 
  5.     (byte)(x >>>  8), 
  6.     (byte)(x >>>  0) 
  7.   }; 
  8.  
  9. byte[] unpackLittleEndian(int x) { 
  10.   return new byte[] { 
  11.     (byte)(x >>>  0), 
  12.     (byte)(x >>>  8), 
  13.     (byte)(x >>> 16), 
  14.     (byte)(x >>> 24) 
  15.   }; 
  16. }  

网站标题:关于Java一些习惯用法的总结
分享URL:http://cdbrznjsb.com/article/dhhgcoc.html

其他资讯

让你的专属顾问为你服务