将字符串添加到字符串数组中

112

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

我有:

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

我希望将新的字符串(string1、string2)添加到这个数组(scripts)中,例如:

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

我希望在初始化之后的阶段添加新字符串,该如何实现?


2
你可以使用 List(例如 ArrayList)吗?或者你可以创建一个更大的新数组,循环旧数组并从索引 = 2 开始添加。然后在索引 01 处添加新元素。 - Nishant
1
所以你不是第一次使用SO,发问前请搜索以避免被踩。 - vels4j
如果需要动态修改元素,请使用java.util.Collections。映射需求和可用的集合类型,对于上述情况,建议使用ArrayList - Vinay Veluri
5个回答

170

你无法在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);

6
请确保还导入了 java.util.ArrayList。 - wizlog

25

首先,这里的代码:

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

应该是

String[] scripts = new String [] {"test3","test4","test5"};
请阅读有关 数组 的教程。
其次,数组是固定大小的,因此您无法向上述数组添加新字符串。 您可以覆盖现有值。
scripts[0] = string1;

(或者)

创建指定大小的数组,然后不断添加元素直到填满。

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


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可以帮助解决你的问题。


1
+1 好的。同样可以使用 System.arrayCopy。 - vels4j
1
你可以使用 Arrays.copyOf() 来实现相同的功能。 - András Kerekes

6
许多答案都建议使用ArrayList更好。 ArrayList的大小不是固定的,而且很容易管理。 它是List接口的可调整大小数组实现。 实现了所有可选列表操作,并允许包括null在内的所有元素。 除了实现List接口外,这个类还提供了方法来操纵用于存储列表的内部数组的大小。 每个ArrayList实例都有一个容量。 容量是用于存储列表中的元素的数组的大小。 它的大小总是至少与列表大小一样大。 当元素被添加到ArrayList中时,它的容量会自动增长。请注意,此实现未同步。
ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接