如何声明一个未知大小的字符串数组?

18

我正在使用Java编程,尝试将一个句子输入到字符串数组中。我正在对其进行分词并确定单词数量。但是,为了确定是否有重复单词,我需要将每个单词添加到字符串数组中。如果我不知道单词数量直到程序后面才能确定,我该如何初始化我的数组?

可能是重复问题:
声明未知大小的数组

  //Declares variables
  Scanner scan = new Scanner (System.in);
  int withoutdup = 0, wordCount = 0;
  String line, word; 
  StringTokenizer tokenizer;
  List<String> sentence = ArrayList<String>;

  //Asks user for input
  System.out.println ("Please enter text. Enter DONE to finish.");
  line = scan.next();


  //Tokenizes the string and counts the number of character and words
while (!line.equals("DONE"))
 {
     tokenizer = new StringTokenizer (line);
     while (tokenizer.hasMoreTokens())
     {
        word = tokenizer.nextToken();
        wordCount++;
        sentence += word; 
     }
     line = scan.next();
 }

那么你应该使用 ArrayList,最后仍然可以转换为数组... - Naytzyrhc
4个回答

32

使用 ArrayList 代替

List<String> list = new ArrayList<String>();

它会自动增长。

为了检查重复项,您可以使用一个SetHashSet),它不允许重复元素。

更新:

我在您的代码中看到了几个问题:

List<String> sentence = ArrayList<String>;
你忘了在等于号后面加上new
sentence += word;

只有当sentence是一个String时,这种方法才能起作用。由于它是一个List,因此您应该在那里使用List.add方法。

sentence.add(word);

现在 wordCount++; 是多余的,sentence.size() 可以告诉您有多少个单词。


抱歉,我对此还不是很熟悉,但以下是我关于输入句子的代码: System.out.println("请输入文本。输入DONE以完成。"); line = scan.next(); while (!line.equals("DONE")) { tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { word = tokenizer.nextToken(); wordCount++; } line = scan.next(); }我该如何声明一个数组列表?因为List<String> sentence = ArrayList<String>();无法工作。 - user1755178
@user1755178:你能否更新问题本身,附上代码? - Bhesh Gurung
@user1755178:我在你的代码中添加了一些注释,请查看更新。 - Bhesh Gurung

6

只需要看下面的例子,你就能理解如何声明一个大小未知的字符串数组了。

首先,使用ArrayList来存储字符串,并每次调用.add方法时,ArrayList的大小都会增加一个元素。在填充ArrayList时,使用ArrayList的size()方法创建并确定您的String数组的大小。但要确保ArrayList中的每个元素都是一个对象,因此您需要将每个元素转换为字符串。

示例:

ArrayList list = new ArrayList();

for( int i = 0; i < 100; i++ )

list.add( "stuff" );

String[] strArray = new String[ list.size() ];

for( int j = 0; j < strArray.length; j++ )

strArray[ j ] = list.get( j ).toString();

希望这能对您有所帮助。这只是一种方法,但我认为可能还有另一种更有效的方式可以完成同样的事情。


2

不可能,数组长度是固定的。最好使用java.util.List实现,例如ArrayList,LinkedList等...

如果你坚持要使用数组,则可以使用这样的函数来调整数组大小,但是这里又会创建一个新的具有新大小的数组,并复制以前的数组值。

private static Object resizeArray (Object oldArray, int newSize) {
   int oldSize = java.lang.reflect.Array.getLength(oldArray);
   Class elementType = oldArray.getClass().getComponentType();
   Object newArray = java.lang.reflect.Array.newInstance(
         elementType, newSize);
   int preserveLength = Math.min(oldSize, newSize);
   if (preserveLength > 0)
      System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
   return newArray; 
}

2

使用可以根据需要缩小和扩大的动态结构,例如ArrayList


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接