zoukankan      html  css  js  c++  java
  • 在不允许新建对象的条件下,将list中指定条件的值去除

    在不允许新建对象的条件下,将list中指定条件的值去除

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    package com.liujianwang.learning;
     
    import java.util.LinkedList;
    import java.util.List;
     
    public class ListTest {
     
        public static void main(String[] args) {
            /*
             * 在不允许新建对象的条件下,将list中指定条件的值去除。
             * 例如:移除list中值大于6的元素。
             */
             
            //测试数据
            List<Integer> list = new LinkedList<Integer>();
            for(int i = 0; i < 10; i++) {
                list.add(i);
            }
             
            //方案一:正序,考虑索引取值问题
    //      removeListAsc(list);
             
            //方案二:倒序,可避免索引取值问题。
            removeListDesc(list);  
             
            System.out.println(list);
             
        }
        /**
         * 方案一:正序处理,考虑索引取值问题。
         */
        private static void removeListAsc(List<Integer> list) {
            for(int i = 0; i < list.size(); i++) {
                if (list.get(i) > 6) {
                    list.remove(i);
                    i--;
                }
            }
        }  
         
        /**
         * 方案二:倒序处理,可避免索引问题。
         */
        private static void removeListDesc(List<Integer> list) {
            for(int i = (list.size() - 1); i >= 0; i--) {
                if (list.get(i) > 6) {
                    list.remove(i);
                }
            }
        }  
    }
  • 相关阅读:
    selenium(六)Page Object模式(使用selenium的PageFactory)
    CodeForces 1325C Ehab and Path-etic MEXs(思维)
    CodeForces 1325D Ehab the Xorcist(异或和+算数和)
    家庭房产(模拟)
    取硬币(思维)
    Xor and Sum(异或和+算术和)
    一元三次方程求解(数学、二分)
    最大最小公倍数 (数学、贪心)
    天梯---球队“食物链”(DFS+剪枝)
    HDU-4857 逃生(逆向拓扑排序)
  • 原文地址:https://www.cnblogs.com/gendan5/p/11430763.html
Copyright © 2011-2022 走看看