【问题标题】:ArrayList to ArrayArrayList 到数组
【发布时间】:2013-01-08 20:48:28
【问题描述】:

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

String[] textfile = ... ;

这些值是字符串(文本文件中的单词),并且有超过 1000 个单词。在这种情况下,我不能执行 words.add("") 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);
        }

【问题讨论】:

  • 为什么你不能做words.add(...) 1000 次?
  • 很难理解你问题的本质。调用 words.add() 1000 次有什么问题?
  • 我首先要问为什么你想要一个字符串数组?除非您有一个只接受数组的 API,否则您可以使用 List 代替数组。特别是考虑到ArrayList 由数组支持。

标签: java arrays algorithm arraylist


【解决方案1】:

你可以使用

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

相关文档

【讨论】:

    【解决方案2】:

    words.toArray() 应该可以正常工作。

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

    【讨论】:

    • 我认为这会导致 ClassCastException。
    【解决方案3】:

    您可以使用 Collection 的 toArray 方法,如下所示

    Collection toArray example

    【讨论】:

      【解决方案4】:
      List<String> words = new ArrayList<String>();
      words.add("w1");
      words.add("w2");
      String[] textfile = new String[words.size()];
      textfile = words.toArray(textfile);
      

      【讨论】:

        猜你喜欢
        • 2018-11-26
        • 2023-03-31
        • 1970-01-01
        • 2012-02-15
        • 2015-09-27
        • 2018-01-24
        • 1970-01-01
        相关资源
        最近更新 更多