ArrayList

时间:2017-08-07 18:36:55

标签: java arraylist netbeans

以下代码搜索给定用户输入的文件,如果匹配,匹配的行将添加到ArrayList。

我似乎遇到了ArrayList的问题,因为我在ArrayList上得到java.util.ConcurrentModificationException。

此问题之前已经得到解答,但我仍然不明白我的代码中的问题导致了这个问题。

任何帮助都将不胜感激。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


public class Test {

    public static void main(String[] args)
    {
        String givenAccnt;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter an account...");
        givenAccnt = scan.nextLine();
        findPasswords(givenAccnt);
    } 

    private static void findPasswords(String userInput)
    {
        File file = new File("C:\\Users\\Nuno\\Documents\\my_passwords.txt");   //file to search
        Scanner scan = new Scanner(System.in);                                  //Scanner object to get user input
        String accntToken;                                                      //first string token of a line, i.e. "account"
        String getLine;                                                         //this is the line that contains the password the user is looking for. There may be +1 lines thus I have to return them all.*** must use ArrayList of strings (lines of strings) instead of Array
        ArrayList<String> collectedLines = new ArrayList<>();                   //any matched line(s) is collected to an ArrayList of strings (lines)
        ListIterator<String> outputMatches =  collectedLines.listIterator();    //iterator for ArrayList... used to iterate and display collected lines to output window
        String nextOutput;                                                      //line(s) that was collected from ArrayList
        boolean isFound = false;
        int i;                                                                  //delineator... finds index of 1st space " " on that line  (or try ' '), so we can get to the 1st token of a line i.e. "account"
        int v = 0;                                                              //counter... everytime an input is matched to a line, the line is collected to ArrayList... increas    e v... the pane will also display number of accounts found (i.e. v)

        try
        {   
            Scanner scanFile = new Scanner(file);                               //Scanner object to scan file
            while(scanFile.hasNextLine())                                       //Scanner scans file... until end of file
            {
                getLine = scanFile.nextLine();                                  //gets a line
                i = getLine.indexOf(" ");                                       //get index of substring (account) token
                accntToken = getLine.substring(0, i);                           //gets the account (1st string token in the line, after " ")                        
                if(userInput.equalsIgnoreCase(accntToken))                      //if given input account equals the account on the line 
                {     
                    collectedLines.add(getLine);                                //append the line to the ArrayList collectedLines
                    isFound = true;                                             //flag
                    v++;                              //increment number of matches found
                }
            }
            System.out.println(v + " matches were found and added to the ArrayList!"); //tests to see search algorithm is working
            while(outputMatches.hasNext())                                      //loop iterates the ArrayList to write collectedLines to the dialog
            {
                nextOutput = (String)outputMatches.next();                      //get line(s) from the ArrayList

                if(!isFound)
                {
                } else 
                    {
                        System.out.println("Passwords found: " +nextOutput);
                        outputMatches.remove();
                    }
            }                  
        }catch (FileNotFoundException ex) 
        {
            Logger.getLogger(PassLock_Main.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error processing file!");
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

执行以下操作时会出现问题:

  1. ArrayList
  2. 获取迭代器(或列表迭代器)
  3. 修改ArrayList(在您的情况下,您为add()
  4. 使用第1项中的迭代器
  5. 您需要避免修改要迭代的列表,或者使用一些支持并发修改+迭代的集合实现。

    例如,您可以尝试使用CopyOnWriteArrayList,但请注意,每次修改时都会复制列表。

    更新:在您的情况下,您只需在修改集合后获取迭代器。尝试移动

    ListIterator<String> outputMatches =  collectedLines.listIterator();
    

    在以下行之后:

    System.out.println(v + " matches were found and added to the ArrayList!");