How do I remove objects from an array in Java?

前端 未结 20 1366
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:39

    [If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]

    To flesh out Dustman's idea:

    List<String> list = new ArrayList<String>(Arrays.asList(array));
    list.removeAll(Arrays.asList("a"));
    array = list.toArray(array);
    

    Edit: I'm now using Arrays.asList instead of Collections.singleton: singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c").

    Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:

    array = list.toArray(new String[0]);
    

    Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:

    private static final String[] EMPTY_STRING_ARRAY = new String[0];
    

    Then the function becomes:

    List<String> list = new ArrayList<>();
    Collections.addAll(list, array);
    list.removeAll(Arrays.asList("a"));
    array = list.toArray(EMPTY_STRING_ARRAY);
    

    This will then stop littering your heap with useless empty string arrays that would otherwise be newed each time your function is called.

    cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:

    array = list.toArray(new String[list.size()]);
    

    I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).

    0 讨论(0)
  • 2020-11-22 01:42

    My little contribution to this problem.

    public class DeleteElementFromArray {
    public static String foo[] = {"a","cc","a","dd"};
    public static String search = "a";
    
    
    public static void main(String[] args) {
        long stop = 0;
        long time = 0;
        long start = 0;
        System.out.println("Searched value in Array is: "+search);
        System.out.println("foo length before is: "+foo.length);
        for(int i=0;i<foo.length;i++){ System.out.println("foo["+i+"] = "+foo[i]);}
        System.out.println("==============================================================");
        start = System.nanoTime();
        foo = removeElementfromArray(search, foo);
        stop = System.nanoTime();
        time = stop - start;
        System.out.println("Equal search took in nano seconds = "+time);
        System.out.println("==========================================================");
        for(int i=0;i<foo.length;i++){ System.out.println("foo["+i+"] = "+foo[i]);}
    }
    public static String[] removeElementfromArray( String toSearchfor, String arr[] ){
         int i = 0;
         int t = 0;
         String tmp1[] = new String[arr.length];     
             for(;i<arr.length;i++){
                  if(arr[i] == toSearchfor){     
                  i++;
                  }
                 tmp1[t] = arr[i];
                 t++;
         }   
         String tmp2[] = new String[arr.length-t];   
         System.arraycopy(tmp1, 0, tmp2, 0, tmp2.length);
         arr = tmp2; tmp1 = null; tmp2 = null;
        return arr;
    }
    

    }

    0 讨论(0)
  • 2020-11-22 01:42

    Will copy all elements except the one with index i:

    if(i == 0){
                    System.arraycopy(edges, 1, copyEdge, 0, edges.length -1 );
                }else{
                    System.arraycopy(edges, 0, copyEdge, 0, i );
                    System.arraycopy(edges, i+1, copyEdge, i, edges.length - (i+1) );
                }
    
    0 讨论(0)
  • 2020-11-22 01:43

    Use:

    list.removeAll(...);
    //post what char you need in the ... section
    
    0 讨论(0)
  • 2020-11-22 01:44

    You can use external library:

    org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)
    

    It is in project Apache Commons Lang http://commons.apache.org/lang/

    0 讨论(0)
  • 2020-11-22 01:45

    See code below

    ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));
    a.remove(i);
    strings = new String[a.size()];
    a.toArray(strings);
    
    0 讨论(0)
提交回复
热议问题