使用iterator出现的死循环

 1  public static void main(String[] args)
 2     {
 3         List<String> list = new ArrayList<String>();
 4         
 5         list.add("yaoyuan");
 6         list.add("tiancai");
 7         
 8         Iterator it = list.iterator();
 9         String s = "";
10         while(it.hasNext()){
11             System.out.println("aaa");
12             if(s == null){
13                 System.out.println("@@@");
14                 continue;
15             }
16 //            System.out.println(it.next());
17             if(((String)it.next()).equals("yaoyuan")){
18                 it.remove();
19                 
20             }
21         }
22         for (String string : list)
23         {
24             System.out.println(string);
25         }
26     }

在以上代码中,若临时变量s为空的话,则会进入死循环。

这是由于没有正确的理解continue的用法,continue会结束其后跟随的语句而直接开始下一次的循环,在这里s为空,则直接进行下一次循环,没有执行到it.next(),所有iterator的序列值没有发生变化,hasNext永远都是真,进入死循环。

 

另外,在对集合做遍历操作的时候不允许有插入或者删除操作,否则会抛异常。若要删除可以使用iterator的remove方法,也可以在元素中做一个标记,循环结束后再做操作。

转载于:https://www.cnblogs.com/yaoyuan23/p/5586769.html

以下代码在曾经调试过程中可能出现的问题#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <iterator> using namespace std; typedef istream_iterator<string> string_input; void welcome() { cout << "******************* 变位词查找系统*********************\n" << "在词典中找出给定的字符串的所有变位词" << endl; } void readDict(vector<string> & dictionary) { cout << "首先,请输入词典的文件名称:" << endl; string dictionary_name; cin >> dictionary_name; ifstream ifs(dictionary_name.c_str()); if (!ifs.is_open()) { cerr << "异常:文件"<< dictionary_name << "没有找到 " << endl; exit(1); } cout << "词典读入中 ..." << flush; copy(string_input(ifs), string_input(), back_inserter(dictionary)); sort(dictionary.begin(),dictionary.end()); cout << "词典包含有 " << dictionary.size() << " 个单词\n\n"; ifs.close(); } void analyseAnagram(const vector<string> & dictionary) { cout << "请输入单词(或任意字母序列)" << endl; for (string_input p(cin); p != string_input(); ++p) { cout << "查找输入单词的变位词中..." << endl; string word = *p; sort(word.begin(), word.end()); bool found_one = false; do { if (binary_search(dictionary.begin(), dictionary.end(), word)) { cout << " " << word ; found_one = true; } } while (next_permutation(word.begin(), word.end())); if (!found_one) cout << " 抱歉,没有找到变位词\n"; cout << "\n请输入下一个单词 " << "(或输入Ctrl+Z终止程序 ) \n" << endl; } } int main() { welcome(); vector<string> dictionary; readDict(dictionary); analyseAnagram(dictionary); system("pause"); return 0; }
最新发布
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值