102

我是 Java 新手,所以我需要一点帮助

我有

String [] scripts = new String [] ("test3","test4","test5");

我想将新字符串(string1,string2)添加到这个数组(脚本)中,例如

String string1= " test1"
String string2 = "test2"

我想在 init 中而不是在后期添加新字符串

我该怎么做?

4

5 回答 5

154

您无法在 java 中调整数组的大小。

一旦声明了数组的大小,它就保持固定。

相反,您可以使用ArrayList具有动态大小的,这意味着您不必担心它的大小。如果您的数组列表不足以容纳新值,那么它将自动调整大小。

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);
于 2012-12-31T06:01:19.877 回答
23

首先,这里的代码,

string [] scripts = new String [] ("test3","test4","test5");

应该

String[] scripts = new String [] {"test3","test4","test5"};

请阅读有关数组的本教程

第二,

数组是固定大小的,所以你不能在上面的数组中添加新的字符串。您可以覆盖现有值

scripts[0] = string1;

(或者)

创建具有大小的数组,然后继续添加元素直到它满了。

如果您想要可调整大小的数组,请考虑使用ArrayList

于 2012-12-31T06:01:29.207 回答
10

你必须写下一些方法来创建一个临时数组,然后像这样复制它

public String[] increaseArray(String[] theArray, int increaseBy)  
{  
    int i = theArray.length;  
    int n = ++i;  
    String[] newArray = new String[n];  
    for(int cnt=0;cnt<theArray.length;cnt++)
    {  
        newArray[cnt] = theArray[cnt];  
    }  
    return newArray;  
}  

ArrayList将有助于解决您的问题。

于 2012-12-31T06:06:06.987 回答
6

由于许多建议更好的解决方案的答案是使用 ArrayList。ArrayList 大小不固定,易于管理。

它是 List 接口的可调整大小的数组实现。实现所有可选列表操作,并允许所有元素,包括 null。除了实现 List 接口之外,该类还提供了一些方法来操作内部用于存储列表的数组的大小。

每个 ArrayList 实例都有一个容量。容量是用于存储列表中元素的数组的大小。它总是至少与列表大小一样大。随着元素被添加到 ArrayList,它的容量会自动增长。

请注意,此实现不同步。

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");
于 2012-12-31T08:42:45.207 回答
4

由于 Java 数组包含固定数量的值,因此在这种情况下,您需要创建一个长度为 5 的新数组。更好的解决方案是使用ArrayList并简单地字符串添加到数组中。

例子:

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test3");
scripts.add("test4");
scripts.add("test5");

// Then later you can add more Strings to the ArrayList
scripts.add("test1");
scripts.add("test2");
于 2012-12-31T06:06:12.567 回答