简体   繁体   中英

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

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).

Your method return type should list. Then you can call that method by object reference or static variable.

The problem you are having can be understood by learning variable scope, move and define your listOfWords out of the while loop.

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;

listOfWords is a local method variable, its scope is restricted to the while loop. Therefore it can't be accessed by another method. There're two ways to deal with it:

  1. The first method can return listOfWords and is called in search() .
  2. If both methods are in the same class, listOfWords can be a class field, which all the methods in the class can accessed.

i will answer your question from your topic : you need to define your array list in the class body (out of the function body) and set it as a public and ( if you wanna access with out initiate your class just set it as static) :

class A 
{

 public static List<String> listOfWords = new ArrayList<String>();
void func()
   {  
//......
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();

} }

here how to access from your class B:

 class B
{
   funcInClassB ()
 {
   myArrayList=A.listOfWords();
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM