4 回答
TA贡献1712条经验 获得超3个赞
public static void main(String[] args) {
String[] stringArray = new String[] {"one", "two", "three"};
method(stringArray);
}
public static String[] method(String[] stringArray) {
String[] biggerStringArray = new String[stringArray.length * 2];
for (int i = 0; i < stringArray.length; i++) {
biggerStringArray[i + biggerStringArray.length / 2] = stringArray[i];
}
for (int i = 0; i < biggerStringArray.length; i++) {
System.out.print(biggerStringArray[i] + ", ");
}
return biggerStringArray;
}
编辑:刚刚记得您还可以使用System.arraycopy:
public static String[] method(String[] stringArray) {
String[] biggerStringArray = new String[stringArray.length * 2];
System.arraycopy(stringArray, 0, biggerStringArray, biggerStringArray.length / 2, stringArray.length);
for (int i = 0; i < biggerStringArray.length; i++) {
System.out.print(biggerStringArray[i] + ", ");
}
return biggerStringArray;
}
TA贡献1815条经验 获得超6个赞
您可以首先创建一个长度等于stringArray. 然后,您可以stringArray使用任何 Java 数组连接方法将 与新的空数组连接起来。
这是一个例子
public static String[] method(String[] stringArray) {
String[] nullArray = new String[stringArray.length];
String[] biggerStringArray = Stream.of(nullArray, stringArray).flatMap(Stream::of).toArray(String[]::new);
// for (int i = 0; i < biggerStringArray.length; i++) {
// System.out.print(biggerStringArray[i] + ", ");
// }
return biggerStringArray;
}
TA贡献1982条经验 获得超2个赞
据我所知,不存在执行您正在寻找的操作的单个语句。但这并不意味着您不能自己做。有很多方法可以交换数组中的元素。这是一个:
String[] biggerStringArray = Arrays.copyOf(stringArray, stringArray.length * 2);
for(int i = 0; i < stringArray.length; i++)
{
biggerStringArray[i] = biggerStringArray[i + stringArray.length];
biggerStringArray[i + stringArray.length] = null;
}
TA贡献1871条经验 获得超8个赞
public static String[] method(String[]stringArray) {
String[] biggerStringArray = Arrays.copyOf(stringArray, stringArray.length * 2);
List<String> biggerStringList = Arrays.asList(biggerStringArray);
biggerStringList.sort(Comparator.nullsFirst(String::compareTo));
System.out.println(biggerStringList);
return biggerStringList.toArray(new String[biggerStringList.size()]);
}
添加回答
举报