Java string[] partial copying

后端 未结 3 336
死守一世寂寞
死守一世寂寞 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 colors = new LinkedHashSet<>();
    colors.add("Red");
    colors.add("Orange");
    colors.add("Yellow");
    ...
    /* Later, create a copy and modify it. */
    Set noRed = new TreeSet<>(colors);
    noRed.remove("Red");
    /* Alternatively, remove the first element that was inserted. */
    List shorter = new ArrayList<>(colors);
    shorter.remove(0);
    

    For inter-operating with array-based legacy APIs, there is a handy method in Collections:

    List colors = new ArrayList<>();
    String[] tmp = colorList.split(", ");
    Collections.addAll(colors, tmp);
    

提交回复
热议问题