How do I remove objects from an array in Java?

前端 未结 20 1369
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 02:03

    EDIT:

    The point with the nulls in the array has been cleared. Sorry for my comments.

    Original:

    Ehm... the line

    array = list.toArray(array);
    

    replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!

    If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:

            String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
    
            System.out.println(Arrays.toString(array));
    
            Set<String> asSet = new HashSet<String>(Arrays.asList(array));
            asSet.remove("a");
            array = asSet.toArray(new String[] {});
    
            System.out.println(Arrays.toString(array));
    

    Gives:

    [a, bc, dc, a, ef]
    [dc, ef, bc]
    

    Where as the current accepted answer from Chris Yester Young outputs:

    [a, bc, dc, a, ef]
    [bc, dc, ef, null, ef]
    

    with the code

        String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
    
        System.out.println(Arrays.toString(array));
    
        List<String> list = new ArrayList<String>(Arrays.asList(array));
        list.removeAll(Arrays.asList("a"));
        array = list.toArray(array);        
    
        System.out.println(Arrays.toString(array));
    

    without any null values left behind.

    0 讨论(0)
  • 2020-11-22 02:04

    An alternative in Java 8:

    String[] filteredArray = Arrays.stream(array)
        .filter(e -> !e.equals(foo)).toArray(String[]::new);
    
    0 讨论(0)
提交回复
热议问题