您的位置:首頁 > 軟件資訊 > 編程技巧 > 網(wǎng)站開發(fā)
來源:北大青鳥飛迅校區(qū)|發(fā)布時(shí)間:2013-04-18 19:03:39
Jython的發(fā)展之道:性能,性能,性能!常見錯(cuò)誤4# :自編代碼來拷貝數(shù)組
Java允許你克隆數(shù)組,但是開發(fā)者通常會(huì)錯(cuò)誤地編寫如下的代碼,問題在于如下的循環(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. }
這段代碼是正確的,但卻不必要地復(fù)雜。saveCopy()的一個(gè)更好的實(shí)現(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ù)組,編寫如下的一個(gè)工具方法會(huì)是個(gè)好主意:
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看起來就更簡(jiǎn)潔了:
1. void saveCopy (int[] data){
2. copy = cloneArray ( data);
3. }
五、常見錯(cuò)誤5#:拷貝錯(cuò)誤的數(shù)據(jù)
有時(shí)候程序員知道必須返回一個(gè)拷貝,但是卻不小心拷貝了錯(cuò)誤的數(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()
全程面授,不高薪都難
申請(qǐng)成功后,我們將在24小時(shí)內(nèi)與您聯(lián)系
招生熱線: 4008-0731-86 / 0731-82186801
學(xué)校地址: 長沙市天心區(qū)團(tuán)結(jié)路6號(hào)
Copyright © 2006 | 湖南大計(jì)信息科技有限公司 版權(quán)所有
湘ICP備14017520號(hào)-3