Java string [] partial copy

How to take String[] and make a copy of this String[] , but without the first line? Example: if I have this ...

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

How can I create a new line, similar to the colors of the string collection, but without it?

+6
source share
3 answers

You can use Arrays.copyOfRange :

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

Forget about arrays. They are not concepts for beginners. It’s best to invest your time in learning about the API collections.

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

Collections have a convenient method for interacting with legacy array-based APIs:

 List<String> colors = new ArrayList<>(); String[] tmp = colorList.split(", "); Collections.addAll(colors, tmp); 
+8
source
 String[] colors = {"Red", "Orange", "Yellow"}; String[] copy = new String[colors.length - 1]; System.arraycopy(colors, 1, copy, 0, colors.length - 1); 
+5
source

Source: https://habr.com/ru/post/917277/


All Articles