[英]“Resizing” an Array in Java, and sending it back
我需要动态调整数组的大小,而不是猜测数组中将包含多少个元素。 我已经为此完成了代码,但似乎无法正常工作,有人可以帮助我找出问题所在吗! 基本上,当找到匹配项时,我需要继续添加到match数组中(为此实现了另一种方法)。
当前,它仅填充matchs数组,然后为它尝试放入数组中的下一个元素提供ArrayIndexOutOfBoundsException。
这是两个功能。
谢谢
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);
}
}
}
}
公共静态String [] reSize(String [] matchs,int s){
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 。 ArrayLists是具有相同类型的后备数组的列表。
ArrayList遵循一定的调整大小策略(另请参见: ArrayList:大小如何增加? )。 因此,如果元素超过了支持数组的大小,将创建一个新数组,并将“旧”数组中的元素复制过来。
如果确实需要将Array作为返回值,则可以简单地使用List的toArray
方法:
ArrayList<String> matches = new ArrayList<String>();
....
for(....) {
matches.add(someString);
}
....
return matches.toArray(new String[matches.size()]);
public String[] resize(String[] original, int extra) {
// You are right you can't resize an array,
// But we can make a new one with extra amount of indexes
String[] newArray = new String[original.length + extra];
// Then we need to copy the original memory over to the new
// array. This leaves the end of the array all null.
System.arrayCopy(original, 0, newArray, 0, original.length);
// Then return it
return newArray;
}
现在,使用此代码时,您必须在调用代码中执行以下操作,
/// ....
if (matches[matches.length-1] != null) {
matches = resize(matches, 10);
}
这是因为如您所述,您无法真正调整数组的大小。 因此,您需要使用resize方法创建的数组替换此堆栈上下文中的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.