18

Possible Duplicate:
Declaring an array of unknown size

I'm working in Java and I am trying to input a sentence into a string array. I am tokenizing it and determining the word count. However, I need to add each word into a string array in order to determine if there are duplicates or not. I am not sure how to initialize my array if I don't know the word count until later in the program.

  //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();
 }
4

4 回答 4

32

Use an ArrayList instead

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

it grows automatically.

To check for the duplicates, you can utilize a Set (HashSet), it doesn't allow duplicate elements.

Update

I see a couple of problem in your code:

List<String> sentence = ArrayList<String>;

You are missing the new after =.

sentence += word;

That only would work if sentence was a String. It's a List so you should use List.add method there

sentence.add(word);

Also now wordCount++; is redundant sentence.size() will tell you how many words.

于 2012-10-18T05:06:50.927 回答
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();

希望这会帮助你。这只是一种方式,但我认为可能还有另一种更有效的方式可以让你做同样的事情。

于 2012-10-18T05:37:55.590 回答
2

Use a dynamic structure which can shrink and grow as needed, ArrayList would be a good choice, for example.

于 2012-10-18T05:07:04.230 回答
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; 
}
于 2012-10-18T05:07:16.183 回答