如何复制一个 String[]
,但是不包括第一个字符串?
例如:如果我有这个...
String[] colors = {"Red", "Orange", "Yellow"};
我应该如何创建一个新的字符串,它与字符串集合“colors”类似,但不包含红色?
您可以使用 Arrays.copyOfRange
方法:
String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
不要考虑数组,对于初学者来说这不是一个容易理解的概念。相比之下,学习集合框架API更值得你投入时间。
/* Populate your collection. */
Set<String> colors = new LinkedHashSet<>();
colors.add("Red");
colors.add("Orange");
colors.add("Yellow");
...
/* Later, create a copy and modify it. */
Set<String> noRed = new TreeSet<>(colors);
noRed.remove("Red");
/* Alternatively, remove the first element that was inserted. */
List<String> shorter = new ArrayList<>(colors);
shorter.remove(0);
为了与基于数组的遗留 API 进行互操作,可以在 Collections
中使用一个方便的方法:
List<String> colors = new ArrayList<>();
String[] tmp = colorList.split(", ");
Collections.addAll(colors, tmp);
String[] colors = {"Red", "Orange", "Yellow"};
String[] copy = new String[colors.length - 1];
System.arraycopy(colors, 1, copy, 0, colors.length - 1);
shorter.remove(0)
来移除第一个元素吧? - SHiRKiT