Initialize variable (Read out of file and store in ArrayList/HashMap) once in Java

I have a program which reads out of files repeatedly. I want to initialize it only once then use the arraylist/HashMAP.

public boolean negative(String text, String type) throws FileNotFoundException
{
     ArrayList<String> negative_list = new ArrayList<String>();
     Scanner scan = new Scanner(new File("NegatingWordList.txt"));
     while (scan.hasNextLine())
     {
           negative_list.add(scan.nextLine());
     }
     if(negative_list.contains(text))
     {
         return true;
     }

    return false;
}

So, after initializing negative_list, I needn't do it again.

Answers


From what I understand, your problem is that you want to save the contents of the file in memory. In that case, globally store your list, initialize to new list when your program starts, in your negative method, if list is empty then read from file into list, after that just check if the list contains the text or not. So after it fills up the list once, it wont read from file again. This will work if your file is not empty. If it is empty, it will read every time. This implementation is simple, therefore, for practice sake you should implement it yourself rather than anybody providing it. You have most of it working anyway.


You can declare negative_list as global variable as below :-

ArrayList<String> negative_list =null;

& inside function use if condition as below :-

if(negative_list == null){
negative_list = new ArrayList<String>();
}

Need Your Help

Writing to stdout from within a Microsoft VBA macro

python vba com excel-vba stdout

I'm using Python (and the Win32 extensions) to execute macros in an Excel spreadsheet via the COM interface, as shown below:

How to install TestNG in eclipse Kepler

eclipse testng

I am trying to install TestNG (which I have never used before) in eclipse Kepler (4.3). I've tried to follow the directions provided on the TestNG site (http://testng.org/doc/download.html), but th...