【问题标题】:How to use an iterator to replace and count如何使用迭代器进行替换和计数
【发布时间】:2015-06-22 22:34:41
【问题描述】:

我无法弄清楚如何使用迭代器替换元素并计算被替换元素的数量。这是我到目前为止的代码:

public class example {
    public static void main (String args[]){
        //create an ArrayList
        ArrayList<String> list = new ArrayList<String>();


        //add elements to the array list
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("B");
        list.add("B");

        //use iterator to display original list
        Iterator iter = list.iterator();
        while (iter.hasNext()){
            Object element = iter.next();
            System.out.println (element + " ");
            }

        // call replace         
        String b = "B";
        String x = "X";
        ArrayList<String> myList = new ArrayList<String>();
        replace (b, x, myList);
    }

    public static <E> int replace(E match, E replacement, ArrayList<E> myList) {

        //throw exceptions if null
            if (match == null){
                throw new IllegalArgumentException ("match cannot be null");
            }
            if (replacement == null){
                throw new IllegalArgumentException ("replacement cannot be null");
            }
            if (myList == null){
                throw new IllegalArgumentException ("myList cannot be null");
            }
            //return 0 if myList is empty
            boolean emptylist = myList.isEmpty();
            if (emptylist = true){
                System.out.println("0");
            }


    }

我已经使用迭代器打印出列表中的元素,但是现在我必须使用迭代器来替换并返回替换的数量。在这种情况下,我想用“X”替换“B”并计算“X”的数量。我假设我想将迭代器放在泛型方法中,但我真的不知道该往哪个方向发展......

【问题讨论】:

    标签: java list iterator listiterator


    【解决方案1】:

    你遍历列表,当你找到一个匹配的元素时,你set它的替换:

    public static <E> int replace(E match, E replacement, ArrayList<E> myList) {
    
        //throw exceptions if null
        if (match == null){
            throw new IllegalArgumentException ("match cannot be null");
        }
        if (replacement == null){
            throw new IllegalArgumentException ("replacement cannot be null");
        }
        if (myList == null){
            throw new IllegalArgumentException ("myList cannot be null");
        }
    
        int counter = 0;
        ListIterator<E> iter = myList.listIterator();
        while (iter.hasNext()) {
            E val = iter.next();
            if (val.equals(match)) {
                iter.set(replacement);
                ++counter;
            }
        }
        return counter;
    }
    

    【讨论】:

    • 你为什么用iter.remove(); iter.add(replacement);而不是iter.set(replacement)? (对iter.remove()iter.add 的每次调用都是ArrayList 的线性时间,因此您已将整个算法设为二次...)
    • @LouisWasserman 好点。不知道为什么我把事情弄得太复杂了——编辑和修复。谢谢!
    • 当我进行您上面描述的更改时,由于某种原因我仍然无法让程序正常工作......因为我在 main 方法中调用了“替换”,不应该它现在用 x 代替 b 吗?还是我还缺少什么?谢谢你的帮助
    • @joe mylist 是一个空的ArrayList。你应该用你在main开头初始化的list调用替换。
    • 哦,哇,愚蠢的错误 - 谢谢。一个后续问题-为什么可以将我的通用列表称为“myList”,但在主要方法中我可以将其称为“列表”?我想我要问的是为什么它们不必被称为同一个东西?
    【解决方案2】:

    尝试使用ListIterator 类,此处记录:http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html

    set 方法的文档描述了如何修改列表元素。

    【讨论】:

      【解决方案3】:

      您不需要迭代器来替换元素,当您在循环时添加或删除元素时需要它。只需简单的 for 循环即可进行替换。

      public class example {
        public static void main (String[] args) throws java.lang.Exception
          {
               ArrayList<String> list = new ArrayList<String>();
      
              //add elements to the array list
              list.add("A");
              list.add("B");
              list.add("C");
              list.add("D");
              list.add("B");
              list.add("B");
      
              String b = "B";
              String x = "X";
      
             System.out.print(replace (b, x, list));            
      
          }
      
          public static <E> int replace(E match, E replacement, ArrayList<E> myList) {
              //throw exceptions if null
                  if (match == null || replacement == null || myList == null ){
                      throw new IllegalArgumentException ("match cannot be null");
                  }
      
                  int i=0;
                  int replaceCount=0;            
                  for(E str : myList){
                      if(str.equals(match)){
                          myList.set(i,replacement);
                          replaceCount++;
                      }
                      i++;
                  }
              return replaceCount;
              }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 1970-01-01
        • 2020-12-05
        • 1970-01-01
        • 2017-04-15
        • 1970-01-01
        • 2016-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多