java 引用類型的數據傳遞的是內存地址實例
java 引用類型的數據傳遞的是內存地址
java中引用類型的數據,傳遞的是內存地址,像類,數組,接口,String等等都是引用類型!
看下面的代碼和截圖
public class Test2 { // java中引用類型的數據傳遞的是內存地址 private Map<String, Student> students = new Hashtable<String, Student>(); public void myTest() { Student student1 = new Student("令狐沖", 16, "華山派", 19888.66); Student student2 = new Student("韋小寶", 15, "紫禁城", 99999.99); Student student3 = new Student("張無忌", 18, "光明頂", 18888.88); students.put("1", student1); students.put("2", student2); students.put("3", student3); Iterator<Map.Entry<String, Student>> entries = students.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, Student> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); entry.getValue().setAge(entry.getValue().getAge() + 1); } } public void myTest2(){ List<String[]> citys = new ArrayList<String[]>(); String [] cityNames = {"贛州市", "於都縣", "江西省", "中國", "贛南地區"}; citys.add(cityNames); for (int index = 0; index < citys.size(); index++) { String[] mycityNames = citys.get(index); for (int i = 0; i < mycityNames.length; i++) { System.out.println(mycityNames[i]); if (i == 1) { //修改mycityNames數組 (java中引用類型的數據傳遞的是內存地址) mycityNames[i] = "我們" + mycityNames[i]; } } System.out.println("--------------------------------"); for (int i = 0; i < mycityNames.length; i++) { System.out.println(mycityNames[i]); } } System.out.println("--------------------------------"); //修改cityNames數組 (java中引用類型的數據傳遞的是內存地址) cityNames[0] = "我們贛州市"; for (int index = 0; index < citys.size(); index++) { String[] mycityNames = citys.get(index); for (int i = 0; i < mycityNames.length; i++) { System.out.println(mycityNames[i]); } } } public static void main(String[] args) { Test2 test2 = new Test2(); test2.myTest(); System.out.println("--------------------------------"); Iterator<Map.Entry<String, Student>> entries = test2.students.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, Student> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } test2.myTest2(); } }
list集合存引用數據類型時的問題
集合list的存儲元素
(1)如果list中存的是基本數據類型,則存的是值
(2)如果list中存的是引用數據類型(如對象等),則存的是引用
如果對象的引用地址沒變,內容變化,也會引起調用該對象時內容變化
下面舉一個在集合list中存放對象的例子:
//構建原始數據 ArrayList<Goods> list = new ArrayList(); Goods goods1=new Goods("plum ", 2); list.add(goods1); list.add(new Goods("apple", 1)); list.add(new Goods("banana", 2)); //打印原始數據 System.out.println("原始數據:"); for(Goods goods : list){ System.out.println(goods); } goods1.setGoodsId(444);//改變goods1的內容 System.out.println("原始數據1:"); for(Goods goods : list){ System.out.println(goods); }
結果:
原始數據:
Goods{goodsName=’plum ‘, goodsId=2}
Goods{goodsName=’apple’, goodsId=1}
Goods{goodsName=’banana’, goodsId=2}
原始數據1:
Goods{goodsName=’plum ‘, goodsId=444}
Goods{goodsName=’apple’, goodsId=1}
Goods{goodsName=’banana’, goodsId=2}
結果表明:由於list中存儲對象的引用所指的內容發生瞭變化,所以導致瞭list中元素內容的改變
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。