Friday, April 04, 2025

2007/08/02

Array copy and assign


Array assign:
int em01[] = {35000, 32000, 35000, 28000, 30000};
int em02[] = em01;
em01[0] = 25000;
System.out.println("em01[0] = " + em01[0]);
System.out.println("em02[0] = " + em02[0]);

result:
em01[0] = 25000
em02[0] = 25000
Array 在assign的時候,是將記憶體位址指定到em02,所以em01和em02是用同一個記憶體位址,也就是同一個變數

Array copy:
int em01[] = {35000, 32000, 35000, 28000, 30000};
int em02[] = new int[em01.length];
System.arraycopy(em01, 0, em02, 0, em01.length);
em01[0] = 25000;
System.out.println("em01[0] = " + em01[0]);
System.out.println("em02[0] = " + em02[0]);

result:
em01[0] = 25000
em02[0] = 35000
Array在copy的時候,須先宣告一個新的陣列,運用函式庫arraycopy,傳值給em02,因此兩個是屬於不同個變數,因此其中一個改變值的時候,另外一個不會一起改變。另外,不一定要用函式庫才能copy,當然也可以自己寫成是一個一個指定值。

0 comments:

張貼留言

Followers

人氣

   my space tracker
   HP Pavilion

 

Jake Hsiao--Self-trust is the first secret of success.. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com