Java中列表的迭代 [英] Iteration over a list in Java

查看:97
本文介绍了Java中列表的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题如下:

编写一个静态方法子集,该子集使用递归回溯来查找给定列表的每个可能的子列表.列表L的子列表包含0或多个L的元素.您的方法应接受字符串列表作为其参数,并打印可以从该列表的元素创建的每个子列表,每行一个.例如,假设一个名为list的变量存储以下元素:

Write a static method subsets that uses recursive backtracking to find every possible sub-list of a given list. A sub-list of a list L contains 0 or more of L's elements. Your method should accept a List of strings as its parameter and print every sub-list that could be created from elements of that list, one per line. For example, suppose a variable called list stores the following elements:

[Janet, Robert, Morgan, Char]

子集的调用(列表);会产生如下输出:

The call of subsets(list); would produce output such as the following:

[Janet, Robert, Morgan, Char]
[Janet, Robert, Morgan]
[Janet, Robert, Char]
[Janet, Robert]
[Janet, Morgan, Char]
[Janet, Morgan]
[Janet, Char]
[Janet]
[Robert, Morgan, Char]
[Robert, Morgan]
[Robert, Char]
[Robert]
[Morgan, Char]
[Morgan]
[Char]
[]

我的解决方案的一部分要求使用递归回溯:

Part of my solution calls for the use of recursive backtracking:

ListIterator<String> itr = choices.listIterator();
      while (itr.hasNext()) {
         String word = itr.next();
         chosen.add(word);
         itr.remove();
         subsets(choices, chosen, alreadyPrinted);
         chosen.remove(word);
         itr.add(word);
      }

但是我在具有itr.add(word)的行上得到了ConcurrentModificationException.为什么?我认为ListIterator的全部目的是避免该问题?

But I get the ConcurrentModificationException on the line that has itr.add(word). Why? I thought the whole point of the ListIterator is to avoid that problem?

我也尝试过这样解决它:

I also tried solving it like this:

for (String word : choices) {
         List<String> choicesCopy = choices;
         chosen.add(word);
         choicesCopy.remove(word);
         subsets(choicesCopy, chosen, alreadyPrinted);
      } 

我仍然收到并发修改异常....:( 这是怎么回事?完全没有修改原始列表...

I still get a concurrentmodificationexception.... : ( How is this happening? There is no modification of the original list at all...

推荐答案

不完全是,问题是(很可能)您每次进行递归都创建ListIterator().每个列表迭代器都试图修改相同的单词基础列表,从而触发异常.这是不允许的.

Not exactly, the problem is (most probably) that you create ListIterator() each time you go recursive. Each List Iterator is trying to modify the same underlying list of words, which triggers the exception. This is not allowed.

解决方案是每次递归时都提供单词列表的副本.这样,每个列表迭代器都将在其自己的个人列表上工作.

The solution is to provide a copy of the list of words each time you go recursive. Like that, each list iterator will work on its own personal list.

这篇关于Java中列表的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆