6

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?

3 Answers 3

14

You could use Arrays.copyOfRange:

String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
Sign up to request clarification or add additional context in comments.

Comments

8

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

1 Comment

Shouldn't be shorter.remove(0) to remove the first element?
5
String[] colors = {"Red", "Orange", "Yellow"};
String[] copy = new String[colors.length - 1];
System.arraycopy(colors, 1, copy, 0, colors.length - 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.