Pedro
Pedro

Reputation: 51

Change from ArrayList to Array of Strings Java

I have this java method which returns an ArrayList, but I want to return an Array of Strings. The method reads the file words.txt (contains all words with a word on each line), and I want to store those words into an Array of Strings.

Heres the code I already have:

public static ArrayList<String> readFile(){
    File myFile=new File("./src/folder/words.txt");
    Scanner s1=null;

    //Creates ArrayList to store each String aux
    ArrayList<String> myWords = new ArrayList<String>();

    try {
        s1 = new Scanner(myFile);
    }catch (FileNotFoundException e) {

        System.out.println("File not found");
        e.printStackTrace();
    }
    while(s1.hasNext()){
        String aux=s1.next();
        System.out.println(aux);

    }
    s1.close();
    return myWords;
}

Can I change this code to return a String []?

Upvotes: 0

Views: 100

Answers (3)

Manuj
Manuj

Reputation: 44

try using a built in function of collections class .

    ArrayList<String> stringList = new ArrayList<String>();
    stringList.add("x");
    stringList.add("y");
    stringList.add("z");
    stringList.add("a");

    /*ArrayList to Array Conversion */
    /*You can use the toArray method of the collections class and pass the  new String array object in the constructor while making a new String array*/
    String stringArray[]=stringList.toArray(new String[stringList.size()]);

    
    for(String k: stringArray)
    {
        System.out.println(k);
    }

Upvotes: 2

Shahid
Shahid

Reputation: 2330

Add this at last:

String [] arr = myWords.toArray(new String[myWords.size()]);
return arr;

Or simply,

return myWords.toArray(new String[myWords.size()]);

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

You can call List.toArray(String[]) to convert the List<String> to a String[]. I would also prefer a try-with-resources over explicitly closing the Scanner and a List<String> interface. Something like,

public static String[] readFile() { // <-- You could pass File myFile here
    File myFile = new File("./src/folder/words.txt");

    // Creates ArrayList to store each String aux
    List<String> myWords = new ArrayList<>();

    try (Scanner s1 = new Scanner(myFile)) {
        while (s1.hasNext()) {
            String aux = s1.next();
            System.out.println(aux);
        }
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    }
    return myWords.toArray(new String[0]);
}

Upvotes: 2

Related Questions