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);
}
asked Jan 8, 2013 at 20:48
user1883386
991 gold badge4 silver badges13 bronze badges
4 Answers 4
You can use
String[] textfile = words.toArray(new String[words.size()]);
Relevant Documentation
answered Jan 8, 2013 at 20:50
arshajii
130k26 gold badges246 silver badges293 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
words.toArray() should work fine.
List<String> words = new ArrayList<String>();
String[] wordsArray = (String[]) words.toArray();
answered Jan 8, 2013 at 20:50
Juvanis
26k5 gold badges75 silver badges88 bronze badges
1 Comment
arshajii
I think this will cause a ClassCastException.
you can use the toArray method of Collection such as shown here
answered Jan 8, 2013 at 20:51
jethroo
2,1242 gold badges19 silver badges32 bronze badges
Comments
List<String> words = new ArrayList<String>();
words.add("w1");
words.add("w2");
String[] textfile = new String[words.size()];
textfile = words.toArray(textfile);
answered Jan 8, 2013 at 20:52
Avinash T.
2,3692 gold badges16 silver badges23 bronze badges
Comments
lang-java
words.add(...)1000 times?Listin place of an array. Especially given thatArrayListis backed by an array.