简体   繁体   中英

Java string[] partial copying

How do I take a String[] , and make a copy of that String[] , but without the first String? Example: If i have this...

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

How would I make a new string that's like the string collection colors, but without red in it?

你可以使用Arrays.copyOfRange

String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);

Forget about arrays. They aren't a concept for beginners. Your time is better invested learning the Collections API instead.

/* 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);

For inter-operating with array-based legacy APIs, there is a handy method in 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM