众所周知,我们可以通过三种方式从集合中删除条目。
通过使用Collection的remove(Object obj)方法
通过使用List的remove(int index)方法
通过使用Iterator的remove()方法
集合接口添加了方法remove(Object obj),该方法用于从集合中删除指定的元素。
列表接口添加了另一个remove(int index)方法,该方法用于删除该方法中指定索引处的对象。
迭代器接口还添加了remove()方法,该方法用于从Collection中删除当前对象。
现在,我们将看到Collection的remove(Object obj)方法与remove()
Iterator的方法有何不同?
此方法在java.util包中可用。
Collection的remove()方法用于从Collection中移除指定元素的单个对象。
下面给出Collection接口的remove()方法的语法:
boolean remove(Object obj)
此方法的返回类型为boolean,因此如果成功删除元素或对象,则返回true,否则返回false。
如果我们在Collection方法中将null作为参数传递,并且在Collection方法中将其他类型元素作为参数传递,则此方法将引发异常[NullPointerException],我们还将获得一个异常[ClassCastException]。
当我们进行迭代时,假设我们遍历一个列表并仅基于逻辑删除一些元素,如果我们使用Collection remove()方法,则将获得异常ConcurrentModificationException。
示例
//Java程序演示行为 // remove()收集方式 import java.util.*; class RemoveCollectionMethod { public static void main(String[] args) { Collection collection = new LinkedList(); collection.add(10); collection.add(20); collection.add(30); collection.add(40); collection.add(50); System.out.println("Current LinkedList:" + collection); collection.remove(30); System.out.println(" LinkedList:" + collection); } }
输出结果
E:\Programs>javac RemoveCollectionMethod.java E:\Programs>java RemoveCollectionMethod Current LinkedList:[10, 20, 30, 40, 50] LinkedList:[10, 20, 40, 50]
现在,我们将看到如何remove()
迭代的方法从收藏中移除(obj对象)方法会有所不同?
此方法在java.util包中可用。
Iterator的remove()方法删除Collection中的当前对象或元素。
如果使用remove()方法,则不能直接在中间移除指定的元素或随机元素,而不能进行迭代。
Iterator接口的remove()方法的语法如下:
void remove(){}
remove()方法的返回类型为void,因此它不返回任何内容。
如果在调用next()方法之前调用此方法,则此方法将引发异常IllegalStateException 。
当我们进行迭代时,假设我们遍历一个列表并仅基于逻辑删除一些元素,并且如果我们使用Iterator remove()方法,那么那里不会有任何异常。
示例
//Java程序演示行为 // remove()迭代器的方法 import java.util.*; class RemoveIteratorMethod { public static void main(String[] args) { //创建一个Set接口对象 Set set = new HashSet(); //通过使用add()方法在集合中添加一些元素 set.add("Java"); set.add("Python"); set.add("C++"); set.add("Ruby"); set.add("C"); //创建Iterator接口的对象 Iterator itr = set.iterator(); //遍历元素的循环 while (itr.hasNext()) { String str = (String) itr.next(); if (str.equals("C")) itr.remove(); } //Set接口的显示元素 System.out.println("The final list of Iterator :" + set); } }
输出结果
E:\Programs>javac RemoveIteratorMethod.java E:\Programs>java RemoveIteratorMethod The final list of Iterator :[Ruby, Python, C++, Java]