java踩坑

來源:互聯網
上載者:User

標籤:tostring   list   ++   pair   new   import   detail   system   pre   

java只傳遞指標遇到的坑:

 1 import java.util.*; 2  3 public class mapTest { 4 public static class EntryWeight{ 5 public int entryid;  6 public float wordweight; 7 public int getentryid(){return entryid;} 8 public float getwordweigth(){return wordweight;} 9 public String toString() {10 return "id=" + entryid + ", weight=" + wordweight;11  }12  }13 public static void main(String[] args) {14 ArrayList<EntryWeight> entryPairs = new ArrayList<EntryWeight>(5);15 for(int i=0;i<5;i++){16 EntryWeight entryPair = new EntryWeight();17 entryPair.entryid = i;18 entryPair.wordweight = (float)0.5+i;19  entryPairs.add(entryPair);20 System.out.println("entry pair: " + entryPair.getentryid() );21 22  }23 for(int i=0;i<entryPairs.size();i++){24 System.out.println("entrys "+i+" : " + entryPairs.get(i).entryid );25  }26 for(int i=0;i<entryPairs.size();i++){27 System.out.println("entrys "+i+" : " + entryPairs.get(i).wordweight );28  }29 for (Iterator<EntryWeight> iterator = entryPairs.iterator(); iterator.hasNext(); ) {30  System.out.println(iterator.next());31  }32  }33 }

這樣寫是正確的,輸出:

entry pair: 0entry pair: 1entry pair: 2entry pair: 3entry pair: 4entrys 0 : 0entrys 1 : 1entrys 2 : 2entrys 3 : 3entrys 4 : 4entrys 0 : 0.5entrys 1 : 1.5entrys 2 : 2.5entrys 3 : 3.5entrys 4 : 4.5id=0, weight=0.5id=1, weight=1.5id=2, weight=2.5id=3, weight=3.5id=4, weight=4.5

把EntryWeight entryPair = new EntryWeight()放在for迴圈外邊,其他都不改,

public static void main(String[] args) {       ArrayList<EntryWeight> entryPairs = new ArrayList<EntryWeight>(5); EntryWeight entryPair = new EntryWeight(); for(int i=0;i<5;i++){ entryPair.entryid = i; entryPair.wordweight = (float)0.5+i; entryPairs.add(entryPair); System.out.println("entry pair: " + entryPair.getentryid() ); }

輸出變成了這樣:

entry pair: 0entry pair: 1entry pair: 2entry pair: 3entry pair: 4entrys 0 : 4entrys 1 : 4entrys 2 : 4entrys 3 : 4entrys 4 : 4entrys 0 : 4.5entrys 1 : 4.5entrys 2 : 4.5entrys 3 : 4.5entrys 4 : 4.5id=4, weight=4.5id=4, weight=4.5id=4, weight=4.5id=4, weight=4.5id=4, weight=4.5

是因為entryPairs.add()只是把地址傳過來了,並沒有建立一個entryPair,想起早晨師兄還說到這個,這麼快就踩到了。

Java中集合提供的拷貝建構函式只支援淺拷貝而不是深拷貝,這意味著儲存在原有List和複製List中的對象會保持一致,並指向Java堆中同一記憶體位址。

java踩坑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.