【问题标题】:how to dynamically allocate size of string array in java如何在java中动态分配字符串数组的大小
【发布时间】:2014-07-01 14:26:22
【问题描述】:

您好,我是使用 java 的初学者。我有以下代码,我想在其中动态初始化字符串数组 word[],该字符串由总数的大小组成。所有文档 [] 数组中的标记。 我该怎么做?

String []result = {"Shipment of Gold damaged in fire","Delivery of silver arrived in silver truck","shipment of Gold arrived in Truck"};
String []documents = new String[result.length];
    for (int  k =0; k<result.length; ++k){ 
        documents[k] = result[k].toLowerCase();
        System.out.println("document["+k+"] :" + documents[k]);
    }
    /*step 2: Tokenize all documents  and create vocabulary from it*/
    int i=0; 
    String [] word = new String [30]; // how to do dynamic allocation here
    int no_of_tokens=0;

    for(String document:documents){
        StringTokenizer st = new StringTokenizer(document," ");
        System.out.print("tokens in document"+ i +":"+ st.countTokens()+"\n");

        while(st.hasMoreTokens()) {
            word[no_of_tokens]=st.nextToken();
            System.out.print(word[no_of_tokens] + "\n");
            no_of_tokens++;
        }
        i++; 
    }

【问题讨论】:

标签: java arrays dynamic-arrays stringtokenizer


【解决方案1】:

您可以使用ArrayList&lt;String&gt;LinkedList&lt;String&gt;。两者的区别在于adding 元素(LinkedList 快,ArrayList 慢)和getting 元素通过 get(i) 的开销(LinkedList 慢,ArrayList 快)。

【讨论】:

  • 其实ArrayList即使在添加时也会获胜。特别是如果您在创建它时正确估计大小(以最小化调整大小)。
【解决方案2】:

对于这种情况,您可以使用List 接口的实现,例如ArrayList。它会在几乎填满时自动调整大小,因此您不必担心确定正确的初始大小。

你可以这样使用它:

....
/*step 2: Tokenize all documents  and create vocabulary from it*/
int i=0; 
List<String> word = new ArrayList<String>(); // how to do dynamic allocation here
int no_of_tokens=0;

....

while(st.hasMoreTokens()) {
    word.add(st.nextToken());
    System.out.print(word.get(no_of_tokens) + "\n");
    no_of_tokens++;
}

【讨论】:

    【解决方案3】:

    我会使用java.util.ArrayList 而不是静态数组。您无法调整静态数组的大小,但可以创建一个新的、更大的静态数组,然后将初始内容复制过来。

    【讨论】:

      【解决方案4】:

      要么使用List,例如ArrayList,要么使用String.split()而不是StringTokenizer,它会返回一个String[]

      【讨论】:

      • 使用split() 是这个问题的唯一合理答案。 +1 是迄今为止唯一提到它的人。
      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      相关资源
      最近更新 更多