Java中list集合的clean()方法濫用引發的bug

來源:互聯網
上載者:User

標籤:比較   sys   string   調試   商品列表   public   實體類   try   產生   

做的是電商系統,主系統產生訂單後,分別加入到不同的隊列中給另外的三個子系統來非同步處理,訂單和商品是一對多的關係,在實際測試中,發現其中有一個子系統從隊列中擷取到的訂單實體中,商品列表一直為空白,子系統的開發人員一直說是擷取不到值導致。因為這個問題,測試一直沒通過,不得已只能打日誌,反覆排查。最後發現在這個子系統中,從隊列拿到訂單實體後,商品列表是不為空白的,但是在執行了一個方法後,該訂單實體類的商品就為空白了。定位到問題後,調試這個方法,後來發現,整個方法的邏輯都是沒問題的,只是在方法的最後,對傳入的參數列表執行了clean()的操作。

     因為實際項目的業務情境比較複雜,在這裡就設計一個簡單的例子來實際說明。定義一個City 的實體類和Country的實體類

public class City {

private Integer id;

private String name;

    //省略了set和get方法

}

public class Country {

private Integer id;

private String name;

private List<City> listCity; //Country和City是一對多的關係

    //省略了set和get方法   

}

然後寫測試類別運行:

public class Test {

public static void main(String[] args) {

City city1=new City();

city1.setId(1);

city1.setName("廣州");

City city2=new City();

 

city2.setId(2);

city2.setName("上海");

List<City> listCity=new ArrayList<>();

listCity.add(city1);

listCity.add(city2);

 

Country country=new Country();

country.setId(1);

country.setName("中國");

country.setListCity(listCity);

getCity(country.getListCity());

System.out.println("list size:"+country.getListCity().size());

 

}

public static void getCity(List<City> listCity){

listCity.clear();

}

}

運行該程式,運行結果是:list size:0

而如果把getCity方法中listCity.clear()注釋掉,則運行結果為:list size:2

這正是導致項目出現那個bug的原因,其實一般來說,除非已經確定沒有程式用到該集合,否則一般不會在方法的最後執行clear()操作。

知道這個原因後,現在來分析為什麼調用這個方法後會導致這個後果。查看JDKclean()源碼:

 

 

通過讀源碼發現,當調用clean()後,會將集合中的資料全部移走,並且將集合中長度置為0。也就是說該方法調用後,集合會變為空白。

 

 

掃一掃
關注java高高手

Java中list集合的clean()方法濫用引發的bug

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.