JAVA 使用List中的remove方法遇到的坑

红太狼 2022-06-01 01:18 255阅读 0赞

一、问题描述

有个需求是从List过滤掉金额小于0.01的数据,看起来很简单,我却搞了半天,没次数据都没删除干净,都会有四五条没删除。。

二、解决方法

测试了半天,发现for循环写错了,刚开始是这样写的:

  1. for (int i = 0; i < psychoLogistResponseList.size(); i++) {
  2. double Graphicprice = Double.parseDouble(psychoLogistResponseList.get(i).getGraphicprice());//图文价格
  3. double Speechprice = Double.parseDouble(psychoLogistResponseList.get(i).getSpeechprice());//语音价格
  4. double Videoprice = Double.parseDouble(psychoLogistResponseList.get(i).getVideoprice());//视频价格
  5. if(1<=Graphicprice||1<=Speechprice||1<=Videoprice){
  6. psychoLogistResponseList.remove(i);
  7. }

debug调试,发现执行前几次没错,到了最后几次,就会漏一些数据。。。在网上找了下,以下才是正确的写法:

  1. /*
  2. * 正确
  3. */
  4. public static void remove14(List<String> list, String target){
  5. for(int i = list.size() - 1; i >= 0; i--){
  6. String item = list.get(i);
  7. if(target.equals(item)){
  8. list.remove(item);
  9. }
  10. }
  11. print(list);
  12. }
  13. /*
  14. * 正确
  15. */
  16. public static void remove22(ArrayList<String> list, String target) {
  17. final CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<String>(list);
  18. for (String item : cowList) {
  19. if (item.equals(target)) {
  20. cowList.remove(item);
  21. }
  22. }
  23. print(cowList);
  24. }

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读