国产美女一级毛片精品久久久|婷婷影院在线综合免费视频|最新国产午夜精品视频成人|久久精品九九无码免费

常見錯誤4# :自編代碼來拷貝數(shù)組

來源:北大青鳥飛迅校區(qū)|發(fā)布時間:2013-04-18 19:03:39

  Jython的發(fā)展之道:性能,性能,性能!常見錯誤4# :自編代碼來拷貝數(shù)組

  Java允許你克隆數(shù)組,但是開發(fā)者通常會錯誤地編寫如下的代碼,問題在于如下的循環(huán)用三行做的事情,如果采用Object的clone方法用一行就可以完成:

  1. public class Example{

  2. private int[] copy;

  3. /*** Save a copy of ’data’. ’data’ cannot be null.*/

  4. public void saveCopy (int[] data){

  5. copy = new int[data.length];

  6. for (int i = 0; i < copy.length; ++i)

  7. copy[i] = data[i];

  8. }

  9. }

  這段代碼是正確的,但卻不必要地復雜。saveCopy()的一個更好的實現(xiàn)是:

  1. void saveCopy (int[] data){

  2. try{

  3. copy = (int[])data.clone();

  4. }catch (CloneNotSupportedException e){

  5. // Can’t get here.

  6. }

  7. }

  如果你經(jīng)?寺(shù)組,編寫如下的一個工具方法會是個好主意:

  1. static int[] cloneArray (int[] data){

  2. try{

  3. return(int[])data.clone();

  4. }catch(CloneNotSupportedException e){

  5. // Can’t get here.

  6. }

  7. }

  這樣的話,我們的saveCopy看起來就更簡潔了:

  1. void saveCopy (int[] data){

  2. copy = cloneArray ( data);

  3. }

  五、常見錯誤5#:拷貝錯誤的數(shù)據(jù)

  有時候程序員知道必須返回一個拷貝,但是卻不小心拷貝了錯誤的數(shù)據(jù)。由于僅僅做了部分的數(shù)據(jù)拷貝工作,下面的代碼與程序員的意圖有偏差:

  1. import java.awt.Dimension;

  2. /*** Example class. The height and width values should never * be

  3. negative. */

  4. public class Example{

  5. static final public int TOTAL_VALUES = 10;

  6. private Dimension[] d = new Dimension[TOTAL_VALUES];

  7. public Example (){ }

  8.

  9. /*** Set height and width. Both height and width must be nonnegative * or an exception will be thrown. */

  10. public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException{

  11. if (height < 0 || width < 0)

  12. throw new IllegalArgumentException();

  13. if (d[index] == null)

  14. d[index] = new Dimension();

  15. d[index].height = height;

  16. d[index].width = width;

  17. }

  18. public synchronized Dimension[] getValues()

上一篇:C#開發(fā)中的兩個基本原則
下一篇:C#一維數(shù)組和多維數(shù)組有何異同?

熱門話題

招生熱線: 4008-0731-86 / 0731-82186801

學校地址: 長沙市天心區(qū)團結(jié)路6號

Copyright © 2006 | 湖南大計信息科技有限公司 版權(quán)所有

湘ICP備14017520號-3

關(guān)注我們
在線咨詢
嘿,我來幫您!