0

How do I convert this ArrayList's value into an array? So it can look like,

String[] textfile = ... ;

The values are Strings (words in the text file), and there are more than a 1000 words. In this case I cannot do the, words.add("") 1000 times. How can I then put this list into an array?

    public static void main(String[]args) throws IOException
    {
        Scanner scan = new Scanner(System.in);
        String stringSearch = scan.nextLine();

        List<String> words = new ArrayList<String>(); //convert to array
        BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));

        String line;
        while ((line = reader.readLine()) != null) {                
            words.add(line);
        }
4
  • 2
    why can't you do words.add(...) 1000 times?
    – driangle
    Commented Jan 8, 2013 at 20:50
  • It is hard to understand the essence of your question. What is the problem with calling words.add() 1000 times? Commented Jan 8, 2013 at 20:53
  • I would start by asking why you want an array of Strings? Unless you have an API that only takes arrays, you can use List in place of an array. Especially given that ArrayList is backed by an array.
    – Steve Kuo
    Commented Jan 8, 2013 at 21:02
  • possible duplicate of Convert ArrayList<String> to String []
    – A--C
    Commented Jan 8, 2013 at 22:18

4 Answers 4

13

You can use

String[] textfile = words.toArray(new String[words.size()]);

Relevant Documentation

0

words.toArray() should work fine.

List<String> words = new ArrayList<String>();
String[] wordsArray = (String[]) words.toArray();
1
  • 1
    I think this will cause a ClassCastException.
    – arshajii
    Commented Jan 8, 2013 at 20:56
0

you can use the toArray method of Collection such as shown here

Collection toArray example

0
List<String> words = new ArrayList<String>();
words.add("w1");
words.add("w2");
String[] textfile = new String[words.size()];
textfile = words.toArray(textfile);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.