2014-10-26 47 views
0

我需要动态调整数组的大小,而不是猜测它将包含多少个元素。我有这样的代码,但它似乎并没有工作,任何人都可以帮助我找出什么是错的!基本上我需要在找到匹配时继续添加到匹配数组(另一种方法是为此实现的)。“调整大小”在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 
} 

}

+1

为什么不使用ArrayList?它是一个动态数据结构,因此您不需要调整大小。 – 2014-10-26 19:33:31

+0

你不能(即使你可以伪造它)调整数组的大小。这不是他们想要的。数组用于__fixed__数量的数据。这听起来像你可能想要一个'ArrayList'来代替。 – BitNinja 2014-10-26 19:33:41

+0

我需要遵循的参数是 //相反,我也希望您编写(并使用)一种方法,在必要时调整数组的大小。 //然而,你知道数组不能调整大小。 \t \t \t //这意味着你的方法是真的要值从一个小数组复制到一个大阵 \t \t \t //并返回大阵 – 2014-10-26 19:35:24

回答

0

使用一个ArrayList。 ArrayLists是具有相同类型的支持数组的列表。

ArrayLists遵循一定的调整策略(另请参阅:ArrayList: how does the size increase?)。因此,如果元素超过后备数组的大小,将创建一个新数组,并且将复制“旧”数组中的元素。

如果你真的需要有数组作为返回值,你可以简单地使用List的toArray方法:

ArrayList<String> matches = new ArrayList<String>(); 
.... 
for(....) { 
    matches.add(someString); 
} 
.... 
return matches.toArray(new String[matches.size()]); 
0
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方法创建的数组。

相关问题