0

Assuming that I'm running with an object like this like this:

static class fileHandler {
    File fileToHandle;
    ArrayList fileDetails;

    fileHandler(File fileIn) {
        fileToHandle = fileIn;
    }


    public void fileHandling() {

        try {
            Scanner reader = new Scanner(fileToHandle);
            reader.useDelimiter(",");
            while(reader.hasNext()) {
                String s = reader.next();
                fileDetails.add(s);
            }
        } catch (FileNotFoundException e) { System.err.println("File Not Found!"); }
    }
}

How could I make "fileDetails" able to work inside my method?

2
  • Just instantiate a new object of fileDetails type inside your method. fileDetails = new ArrayList<T>(); Commented Apr 27, 2012 at 5:14
  • Also it's good to note that unless you have a specific reason for referring fileDetails from a concrete class, then it's far better to refer to List instead. Makes your programs more flexible. Commented Apr 27, 2012 at 5:30

1 Answer 1

2

Initialize it in your Constructor

fileHandler(File fileIn) {
    fileToHandle = fileIn;
    fileDetails = new ArrayList();
}

or right on definition:

ArrayList fileDetails = new ArrayList();

By the way you should use a generic ArrayList:

ArrayList<String> fileDetails = new ArrayList<String>();

and class names should start with a Uppercase Letter

class FileHandler { 
Sign up to request clarification or add additional context in comments.

6 Comments

Also declare your class fields final, and use getters to access them.
@ortang probaby ment private instead of final
@ortang defining fields as private final in this case would be utterly stupid. He does not need his class to be immutable. It would be silly.
Why not? I see no reason why fileDetails or fileToHandle should change after he created a instance of the class. I have no idea if he wants his class immutable, plus only adding final does not make that class immutable.
in his case it would make it immutable. Since he only has two fields. fileDetails and fileToHandle. And by definition Immutable means unchangeable. In Java, when an object is defined as being immutable it means that once it has been initialized its state cannot be changed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.