6

我如何获取String[], 并复制该String[], 但没有第一个字符串?示例:如果我有这个...

String[] colors = {"Red", "Orange", "Yellow"};

我如何制作一个类似于字符串集合颜色但没有红色的新字符串?

4

3 回答 3

14

你可以使用Arrays.copyOfRange

String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
于 2012-06-03T05:21:44.723 回答
8

忘记数组。它们不是初学者的概念。你最好把时间花在学习 Collections 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);
于 2012-06-03T05:32:44.290 回答
5
String[] colors = {"Red", "Orange", "Yellow"};
String[] copy = new String[colors.length - 1];
System.arraycopy(colors, 1, copy, 0, colors.length - 1);
于 2012-06-03T05:22:49.480 回答