Java引用的深入理解學習
透過幾個小例子,深入理解Java中引用,對象,實用關係
遍歷list
static void methoda() {
List<String> strList = new ArrayList<String>();
String[] strs = {
"A A", "B B", "C C"
};
for (String m : strs) {
strList.add(m);
}
for (String s : strList) {
strList.add(s);
System.out.println("s: " + s);
}
}
很普通的遍歷list, 很顯然遍歷過程對strList修改,會拋出異常java.util.ConcurrentModificationException,產看源碼:
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
發現每次對list迭代,調用next方法時都有檢測list長度是否有更改,有則拋出異常
strList爲實例的一個引用,對strList操作就是對原來的對象操作,程序Carsh.
真的想要遍歷時操作list的化可以這樣:
for (int i =strList.size() - 1 ; i >= 0; i--)
這個程序會崩潰嗎?
同樣的,下面方法目的是依次打印數組中的每個字符.
但是是在循環內部又對要打印的strs變量賦值,程序會按照設計運行嗎?
//Show me the code
static void method(){
String[] strs = {"A A", "B B", "C C"};
for(String s : strs){
strs = s.split(" ");
for(String m : strs){
Ststem.out.println("m: " + m);
}
}
}
這個程序會Crash嗎?會按照程序設計輸出嗎?
首先需要理解 引用 的意思,strs只是數組 {“A A”, “B B”, “C C”} 的一個引用,
此處String 與 List賦值方式不同
list是對其引用操作,導致原對象更改,此處strs = s.split(” “),只是新 new了個對象給strs ,原來的數組並沒有被修改,所以程序正常運行:
輸出:
m: A
m: A
m: B
m: B
m: C
m: C