Java 数组列表到数组

Java 数组列表到数组,java,arrays,algorithm,arraylist,Java,Arrays,Algorithm,Arraylist,如何将此ArrayList的值转换为数组?所以它看起来像 String[] textfile = ... ; 这些值是文本文件中的字符串和单词,并且有1000多个单词。在这种情况下,我无法完成,单词。添加1000次。然后如何将此列表放入数组中 public static void main(String[]args) throws IOException { Scanner scan = new Scanner(System.in); Strin

如何将此ArrayList的值转换为数组?所以它看起来像

String[] textfile = ... ;
这些值是文本文件中的字符串和单词,并且有1000多个单词。在这种情况下,我无法完成,单词。添加1000次。然后如何将此列表放入数组中

    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);
        }
toArray应该很好用

List<String> words = new ArrayList<String>();
String[] wordsArray = (String[]) words.toArray();
你可以用

String[] textfile = words.toArray(new String[words.size()]);
相关文件


您可以使用toArray收集方法,如下图所示


为什么你不能做文字。加上。。。1000次?很难理解你问题的实质。调用words.add 1000次有什么问题?我首先会问,为什么需要字符串数组?除非您有一个只接受数组的API,否则可以使用列表代替数组。特别是考虑到ArrayList是由一个数组支持的。我认为这可能会导致ClassCastException的重复。
List<String> words = new ArrayList<String>();
words.add("w1");
words.add("w2");
String[] textfile = new String[words.size()];
textfile = words.toArray(textfile);