How do I remove objects from an array in Java?

前端 未结 20 1721
Happy的楠姐
Happy的楠姐 2020-11-22 01:20

Given an array of n Objects, let\'s say it is an array of strings, and it has the following values:

foo[0] = \"a\";
foo[1]          


        
20条回答
  •  暖寄归人
    2020-11-22 01:53

    If it doesn't matter the order of the elements. you can swap between the elements foo[x] and foo[0], then call foo.drop(1).

    foo.drop(n) removes (n) first elements from the array.

    I guess this is the simplest and resource efficient way to do.

    PS: indexOf can be implemented in many ways, this is my version.

    Integer indexOf(String[] arr, String value){
        for(Integer i = 0 ; i < arr.length; i++ )
            if(arr[i] == value)
                return i;         // return the index of the element
        return -1                 // otherwise -1
    }
    
    while (true) {
       Integer i;
       i = indexOf(foo,"a")
       if (i == -1) break;
       foo[i] = foo[0];           // preserve foo[0]
       foo.drop(1);
    }
    

提交回复
热议问题