原文: https://beginnersbook.com/2013/12/java-arraylist-removeobject-method-example/

方法remove(Object obj)从列表中删除指定的对象。它属于java.util.ArrayList类。

public boolean remove(Object obj)

注:

  • 如果列表中不存在指定的元素,则返回false
  • 如果列表中存在重复元素,则会从列表中删除指定元素的第一个匹配项。

在这个例子中,我们有一个ArrayList<String>我们正从列表中删除一些字符串。

  1. package beginnersbook.com;
  2. import java.util.ArrayList;
  3. public class RemoveExample {
  4. public static void main(String args[]) {
  5. //String ArrayList
  6. ArrayList<String> al = new ArrayList<String>();
  7. al.add("AA");
  8. al.add("BB");
  9. al.add("CC");
  10. al.add("DD");
  11. al.add("EE");
  12. al.add("FF");
  13. System.out.println("ArrayList before remove:");
  14. for(String var: al){
  15. System.out.println(var);
  16. }
  17. //Removing element AA from the arraylist
  18. al.remove("AA");
  19. //Removing element FF from the arraylist
  20. al.remove("FF");
  21. //Removing element CC from the arraylist
  22. al.remove("CC");
  23. /*This element is not present in the list so
  24. * it should return false
  25. */
  26. boolean b=al.remove("GG");
  27. System.out.println("Element GG removed: "+b);
  28. System.out.println("ArrayList After remove:");
  29. for(String var2: al){
  30. System.out.println(var2);
  31. }
  32. }
  33. }

输出:

  1. ArrayList before remove:
  2. AA
  3. BB
  4. CC
  5. DD
  6. EE
  7. FF
  8. Element GG removed: false
  9. ArrayList After remove:
  10. BB
  11. DD
  12. EE