我需要动态调整数组的大小,而不是猜测它将包含多少个元素。我有这样的代码,但它似乎并没有工作,任何人都可以帮助我找出什么是错的!基本上我需要在找到匹配时继续添加到匹配数组(另一种方法是为此实现的)。“调整大小”在Java中的数组,并将其发回
目前它只是填充matches数组,然后给它尝试放入数组的下一个元素给出ArrayIndexOutOfBoundsException。
以下是2个功能。
由于
private static String[] subStrings(String[] tokens) {
String[] matches;
matches = new String[40]; //creates a new array of matches
for (int i = 0; i <=tokens.length; i++){
for (int j = i+1; j <tokens.length;j++){
if(Text.match(tokens[i],tokens[j])){
matches[i]=(tokens[i]+" | "+tokens[j]);
System.out.println(matches[i]);
if(matches[matches.length-1]!=null){
reSize(matches, matches.length+10);
}
}
}
}
公共静态字符串[]调整尺寸(字符串[]匹配,int类型){
if(s<0){
return null;
}
String BiggerMatch[] = new String[s];
for(int i=0; i< matches.length; ++i){
BiggerMatch[i]=matches[i]; //saves the original array in a temporary variable
}
matches = new String[s]; //adds s integer to the array size of matches
for(int i=0; i<=matches.length - s ; i++){ //leaves s spaces null at the end of the array
matches[i]= BiggerMatch[i];
}
matches = BiggerMatch;
subStrings(matches); //sending the new array back to the subStrings method
return BiggerMatch;//returns the new array
}
}
为什么不使用ArrayList?它是一个动态数据结构,因此您不需要调整大小。 – 2014-10-26 19:33:31
你不能(即使你可以伪造它)调整数组的大小。这不是他们想要的。数组用于__fixed__数量的数据。这听起来像你可能想要一个'ArrayList'来代替。 – BitNinja 2014-10-26 19:33:41
我需要遵循的参数是 //相反,我也希望您编写(并使用)一种方法,在必要时调整数组的大小。 //然而,你知道数组不能调整大小。 \t \t \t //这意味着你的方法是真的要值从一个小数组复制到一个大阵 \t \t \t //并返回大阵 – 2014-10-26 19:35:24