Remove a specific string from an array of string

前端 未结 5 1561
梦谈多话
梦谈多话 2020-12-03 13:45

I have an array like this:

String n[] = {\"google\",\"microsoft\",\"apple\"};

What I want to do is to remove \"apple\".

My problem

5条回答
  •  温柔的废话
    2020-12-03 14:27

    You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.

    You'd be better off with a List, e.g. an ArrayList:

    List list = new ArrayList();
    list.add("google");
    list.add("microsoft");
    list.add("apple");
    System.out.println(list.size()); // 3
    
    list.remove("apple");
    System.out.println(list.size()); // 2
    

    Collections like this are generally much more flexible than working with arrays directly.

    EDIT: For removal:

    void removeRandomElement(List list, Random random)
    {
        int index = random.nextInt(list.size());
        list.remove(index);
    }
    

提交回复
热议问题