杰瑞科技汇

Java中remove方法怎么用?

Of course! In Java, "remove" can mean several different things depending on what you're trying to remove. I'll cover the most common scenarios with clear examples.

Java中remove方法怎么用?-图1
(图片来源网络,侵删)

Removing an Element from a List

This is the most frequent use case. There are two main methods: remove(index) and remove(Object).

remove(int index): Removes by position

This method removes the element at a specific numerical index and returns the element that was removed.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RemoveFromList {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie", "David"));
        System.out.println("Original List: " + names);
        // Remove the element at index 1 (which is "Bob")
        String removedName = names.remove(1);
        System.out.println("Removed Element: " + removedName);
        System.out.println("List after removal: " + names);
    }
}

Output:

Original List: [Alice, Bob, Charlie, David]
Removed Element: Bob
List after removal: [Alice, Charlie, David]

remove(Object): Removes by value

This method removes the first occurrence of a specific object. It returns true if an element was removed, and false otherwise.

Java中remove方法怎么用?-图2
(图片来源网络,侵删)

⚠️ Common Pitfall: If you have a List of Integers, you cannot use remove(1) to remove the integer 1. Java will interpret 1 as an index. You must wrap it in Integer.valueOf(1).

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RemoveFromListByValue {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry", "Apple"));
        System.out.println("Original Fruit List: " + fruits);
        // Remove the first occurrence of "Apple"
        boolean wasRemoved = fruits.remove("Apple");
        System.out.println("Was 'Apple' removed? " + wasRemoved);
        System.out.println("Fruit List after removal: " + fruits);
        List<Integer> numbers = new ArrayList<>(Arrays.asList(10, 20, 30, 20, 40));
        System.out.println("\nOriginal Number List: " + numbers);
        // To remove the Integer value 20, you MUST use Integer.valueOf(20)
        // numbers.remove(20); would try to remove the element at index 20, causing an error!
        numbers.remove(Integer.valueOf(20));
        System.out.println("Number List after removal: " + numbers);
    }
}

Output:

Original Fruit List: [Apple, Banana, Cherry, Apple]
Was 'Apple' removed? true
Fruit List after removal: [Banana, Cherry, Apple]
Original Number List: [10, 20, 30, 20, 40]
Number List after removal: [10, 30, 20, 40]

Removing Elements while Iterating (Advanced)

If you try to remove an element from a list while using a basic for loop or an enhanced for-each loop, you will get a ConcurrentModificationException.

Incorrect Way (Throws Exception)

List<String> names = new ArrayList<>(Arrays.asList("Anna", "Bob", "Charlie", "David"));
for (String name : names) {
    if (name.startsWith("B")) {
        names.remove(name); // Throws ConcurrentModificationException!
    }
}

Correct Ways:

a) Using an Iterator (The Classic Way) This is the safest and most robust method for any collection.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class RemoveWithIterator {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(Arrays.asList("Anna", "Bob", "Charlie", "David"));
        System.out.println("Original List: " + names);
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            String name = iterator.next();
            if (name.startsWith("B")) {
                iterator.remove(); // Correctly removes the last element returned by next()
            }
        }
        System.out.println("List after removal: " + names);
    }
}

Output:

Original List: [Anna, Bob, Charlie, David]
List after removal: [Anna, Charlie, David]

b) Using Java 8 Streams (Modern & Functional) This is a very clean and expressive way to create a new list with the unwanted elements filtered out.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveWithStream {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(Arrays.asList("Anna", "Bob", "Charlie", "David"));
        System.out.println("Original List: " + names);
        // Create a new list containing only elements that do NOT start with "B"
        List<String> filteredNames = names.stream()
                                          .filter(name -> !name.startsWith("B"))
                                          .collect(Collectors.toList());
        System.out.println("Filtered List: " + filteredNames);
    }
}

Output:

Original List: [Anna, Bob, Charlie, David]
Filtered List: [Anna, Charlie, David]

Removing from a Set

A Set (like HashSet) only contains unique elements. The remove(Object) method removes the specified element if it's present.

import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
public class RemoveFromSet {
    public static void main(String[] args) {
        Set<String> uniqueFruits = new HashSet<>(Arrays.asList("Apple", "Banana", "Cherry", "Apple"));
        System.out.println("Original Set: " + uniqueFruits); // Duplicates are automatically gone
        boolean wasRemoved = uniqueFruits.remove("Apple");
        System.out.println("Was 'Apple' removed? " + wasRemoved);
        System.out.println("Set after removal: " + uniqueFruits);
    }
}

Output:

Original Set: [Cherry, Apple, Banana]
Was 'Apple' removed? true
Set after removal: [Cherry, Banana]

Removing from a Map

A Map stores key-value pairs. You can remove based on the key.

remove(Object key): Removes the entry for the specified key.

import java.util.HashMap;
import java.util.Map;
public class RemoveFromMap {
    public static void main(String[] args) {
        Map<Integer, String> userMap = new HashMap<>();
        userMap.put(1, "Alice");
        userMap.put(2, "Bob");
        userMap.put(3, "Charlie");
        System.out.println("Original Map: " + userMap);
        // Remove the entry with key 2
        String removedUser = userMap.remove(2);
        System.out.println("Removed User: " + removedUser);
        System.out.println("Map after removal: " + userMap);
    }
}

Output:

Original Map: {1=Alice, 2=Bob, 3=Charlie}
Removed User: Bob
Map after removal: {1=Alice, 3=Charlie}

remove(Object key, Object value): Removes only if the key is mapped to the specified value.

This is useful for atomic "check-and-remove" operations.

import java.util.HashMap;
import java.util.Map;
public class RemoveFromMapConditional {
    public static void main(String[] args) {
        Map<String, String> settings = new HashMap<>();
        settings.put("theme", "dark");
        settings.put("language", "en");
        System.out.println("Original Map: " + settings);
        // This will only remove "theme" if its value is "light". It's not, so nothing happens.
        boolean removed1 = settings.remove("theme", "light");
        System.out.println("Removed 'theme' with value 'light'? " + removed1);
        // This will remove "theme" because its value is indeed "dark".
        boolean removed2 = settings.remove("theme", "dark");
        System.out.println("Removed 'theme' with value 'dark'? " + removed2);
        System.out.println("Final Map: " + settings);
    }
}

Output:

Original Map: {theme=dark, language=en}
Removed 'theme' with value 'light'? false
Removed 'theme' with value 'dark'? true
Final Map: {language=en}

Summary Table

Data Structure Method Description Example
List remove(int index) Removes element at a specific position. list.remove(1);
List remove(Object o) Removes the first occurrence of an element. list.remove("Bob");
List iterator.remove() Safely removes an element while iterating. it.remove();
List filter() (Stream) Creates a new list without unwanted elements. list.stream().filter(...).collect(...)
Set remove(Object o) Removes the specified element (if present). set.remove("Cherry");
Map remove(Object key) Removes the entry for the specified key. map.remove(1);
Map remove(key, value) Removes entry only if key maps to that value. map.remove("theme", "dark");
分享:
扫描分享到社交APP
上一篇
下一篇