Java string[] partial copying

后端 未结 3 337
死守一世寂寞
死守一世寂寞 2020-12-20 19:25

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

String[] color         


        
相关标签:
3条回答
  • 2020-12-20 19:59

    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);
    
    0 讨论(0)
  • 2020-12-20 20:00

    You could use Arrays.copyOfRange:

    String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
    
    0 讨论(0)
  • 2020-12-20 20:14
    String[] colors = {"Red", "Orange", "Yellow"};
    String[] copy = new String[colors.length - 1];
    System.arraycopy(colors, 1, copy, 0, colors.length - 1);
    
    0 讨论(0)
提交回复
热议问题