简体   繁体   中英

Storing strings from a text file/scanner. Array or built-in?

This code snippet is to to read a text file, turn the lines into objects through a different public (non changeable) class(externalClass).

The external class does nothing but turn strings (lines from the .txt through nextLine) into objects, and is fully functional. The scanner(scanner3) is assigned to the text file.

        while (scanner3.hasNext()) {
               externalClass convertedlines = new externalClass(scanner3.nextLine());

I'm not new to programming, but as I'm new to java, I do not know if this requires me to create an array, or if the returned objects are sorted in some other way. ie is the "importedlines" getting overwritten with each run of the loop(and I need to introduce an array into the loop), or are the objects stored in some way?

The question may seem strange, but with the program I am making it would be harder (but definitely not impossible) if I used an array.

Any help would be appreciated.

As requested, externalClass:

public class exernalClass {
    private String line;

    externalClass(String inLine){   
        line = inLine;
    }

    public String giveLine() {
        return line;
    }
}

You are right, the convertedlines will be overwritten in every run of the loop.

Depending on what you want to do with the lines afterwards and if you know how big the files you read are some implementation of Collection (like an ArrayList or LinkedList ) may be a better fit than an array.

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