Search code examples
javanetbeansjava-6

Access an ArrayList from a method in another class


I am trying to make a program that takes input from a file and then searches for the input in a different file, for example, it takes the word "car" from file A and outputs the location of the word(if the word is included) in file B.

At the moment I have 3 classes. A main class, a class to read the file input and a class to search for the input in another file.

The class that reads the input has code that takes the files, reads the file line by line and saves each word into a variable, and then adds these variables into an arrayList.

This is part of the code:

List<String> listOfWords = new ArrayList<String>();
     while((strLine = br.readLine()) != null){
          String [] tokens = strLine.split("\\s+");
          String [] words = tokens;
          for(String word : words){
              listOfWords.add(word);
              System.out.print(word);
              System.out.print(" ");      
          } 
        System.out.print("\n");  
    }
        in.close();
        return listOfWords;    
    }

I then need to take the arrayList and put it into the class with the code that searches for the words in an external file.

This is part of the code that searches for the words:

public void search(List<String> listOfWords) throws FileNotFoundException, IOException{

        FileInputStream fstream = new FileInputStream(getSearchFileName());

        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while((strLine = br.readLine()) != null){
            for(String list: listOfWords){
            Pattern p = Pattern.compile(list);
            Matcher m = p.matcher(strLine);

        int start = 0;
        while (m.find(start)) {
            System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
            start = m.end();
                }
            }
          }  
}

The code works standalone, but I am having trouble calling the arrayList (listOfWords) from the first set of code and using it in the second set of code, which are in different classes.

Any help with what code I need to add or adjust will be appreciated.

Regards


Solution

  • This seems like a matter of scope. If you're going to use that list across a class or between methods you can consider:

    1. Returning the list on the first method, saving it in a field or variable and passing it to the second method.
    2. Make the list a class field and manage it. That way you'll be able to access it in the second block of code, assuming both blocks are on the same class.

    As it is, the list is defined within the scope of the first block of code (the while loop), which I presume is an extract of an actual method. Once the method is finished, the list is eligible for GC (in other words, as good as discarded).