如何声明大小未知的字符串数组?(复制)

时间:2022-07-05 21:26:36

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.

我在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();
 }

4 个解决方案

#1


29  

Use an ArrayList instead

使用一个ArrayList相反

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.

要检查重复的元素,可以使用Set (HashSet),它不允许重复元素。

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.

现在也wordCount + +;是多余的句子。size()会告诉你有多少个单词。

#2


6  

just see the below example, you will get the idea about how to declare a string array of unknown size.

看看下面的示例,您将了解如何声明大小未知的字符串数组。

First, use ArrayList to store the strings and each time call the .add method the ArrayList size increases by one element. When you're filling the ArrayList, use ArrayList size() method and create your String array and size it from. But make sure that each element in an ArrayList is an Object that’s why you need to convert each element to a String.

首先,使用ArrayList存储字符串,每次调用.add方法时,ArrayList大小增加一个元素。填充ArrayList时,使用ArrayList size()方法创建字符串数组并对其进行大小设置。但是要确保ArrayList中的每个元素都是对象,这就是为什么需要将每个元素转换为字符串的原因。

Example:

例子:

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();

Hope this will help you. It’s just one way, but I think there might be another more efficient way through you can do the same thing.

希望这能对你有所帮助。这只是一种方法,但我认为你可以通过另一种更有效的方式来做同样的事情。

#3


2  

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

使用动态结构可以根据需要进行收缩和增长,例如ArrayList就是一个不错的选择。

#4


2  

Not possible, arrays are constant in length. Its better to use java.util.List implementation like ArrayList,LinkedList etc...

不可能,数组的长度是恒定的。最好使用java.util。列表实现,如ArrayList,LinkedList等等…

If you want to persist with array then you can use such function to resize your array but again here it will create a new array with new size and copy previous arrays value.

如果你想保留数组,你可以使用这个函数来调整数组的大小,但是在这里它会创建一个新的数组并复制之前的数组值。

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; 
}

#1


29  

Use an ArrayList instead

使用一个ArrayList相反

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.

要检查重复的元素,可以使用Set (HashSet),它不允许重复元素。

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.

现在也wordCount + +;是多余的句子。size()会告诉你有多少个单词。

#2


6  

just see the below example, you will get the idea about how to declare a string array of unknown size.

看看下面的示例,您将了解如何声明大小未知的字符串数组。

First, use ArrayList to store the strings and each time call the .add method the ArrayList size increases by one element. When you're filling the ArrayList, use ArrayList size() method and create your String array and size it from. But make sure that each element in an ArrayList is an Object that’s why you need to convert each element to a String.

首先,使用ArrayList存储字符串,每次调用.add方法时,ArrayList大小增加一个元素。填充ArrayList时,使用ArrayList size()方法创建字符串数组并对其进行大小设置。但是要确保ArrayList中的每个元素都是对象,这就是为什么需要将每个元素转换为字符串的原因。

Example:

例子:

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();

Hope this will help you. It’s just one way, but I think there might be another more efficient way through you can do the same thing.

希望这能对你有所帮助。这只是一种方法,但我认为你可以通过另一种更有效的方式来做同样的事情。

#3


2  

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

使用动态结构可以根据需要进行收缩和增长,例如ArrayList就是一个不错的选择。

#4


2  

Not possible, arrays are constant in length. Its better to use java.util.List implementation like ArrayList,LinkedList etc...

不可能,数组的长度是恒定的。最好使用java.util。列表实现,如ArrayList,LinkedList等等…

If you want to persist with array then you can use such function to resize your array but again here it will create a new array with new size and copy previous arrays value.

如果你想保留数组,你可以使用这个函数来调整数组的大小,但是在这里它会创建一个新的数组并复制之前的数组值。

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; 
}