我是Java的新手,所以需要一点帮助。
我有:
String [] scripts = new String [] ("test3","test4","test5");
我希望将新的字符串(string1、string2)添加到这个数组(scripts)中,例如:
String string1= " test1"
String string2 = "test2"
我希望在初始化之后的阶段添加新字符串,该如何实现?
我是Java的新手,所以需要一点帮助。
我有:
String [] scripts = new String [] ("test3","test4","test5");
我希望将新的字符串(string1、string2)添加到这个数组(scripts)中,例如:
String string1= " test1"
String string2 = "test2"
我希望在初始化之后的阶段添加新字符串,该如何实现?
你无法在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);
你需要编写一些方法来创建一个临时数组,然后像复制它一样将其复制。
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可以帮助解决你的问题。
ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");
由于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");
List
(例如ArrayList
)吗?或者你可以创建一个更大的新数组,循环旧数组并从索引 = 2 开始添加。然后在索引0
和1
处添加新元素。 - Nishantjava.util.Collections
。映射需求和可用的集合类型,对于上述情况,建议使用ArrayList
。 - Vinay Veluri