Java中的 LinkedList removeLastOccurrence() 方法示例
Java.util.concurrent.LinkedList.removeLastOccurrence()方法是Java中的一个内置方法,它接受一个参数并删除该元素在列表中的最后一次出现。因此,如果该元素不存在于列表中,则它保持不变。
句法:
public boolean removeLastOccurrence(Object o)
参数:该函数接受一个对象elem作为参数,该参数表示要从列表中删除其最后一次出现的对象。
返回值:如果列表中存在elem ,则该函数返回true ,否则返回false 。
下面的程序说明了removeLastOccurrence()方法的使用:
// Java program to demonstrate removeLastOccurrence()
// method of LinkedList
import java.util.*;
class LinkedListDemo {
public static void main(String[] args)
{
LinkedList list
= new LinkedList();
list.add("GFG");
list.add("Geeks");
list.add("Gfg");
list.add("gfg");
list.add("Geeks");
// Displaying the existing LinkedList
System.out.println("LinkedList: "
+ list);
// Remove last occurrence of element
list.removeLastOccurrence("Geeks");
System.out.println("Removed last occurrence"
+ " of 'Geeks' from the list");
// Displaying the modified LinkedList
System.out.println("LinkedList: "
+ list);
}
}
输出:
LinkedList: [GFG, Geeks, Gfg, gfg, Geeks]
Removed last occurrence of 'Geeks' from the list
LinkedList: [GFG, Geeks, Gfg, gfg]
方案二:
// Java program to demonstrate removeLastOccurrence()
// method of LinkedList
import java.util.*;
class LinkedListDemo {
public static void main(String[] args)
{
LinkedList
list = new LinkedList();
list.add(12);
list.add(280);
list.add(12);
list.add(1050);
list.add(12);
// Displaying the existing LinkedList
System.out.println("LinkedList: "
+ list);
// Remove last occurrence of element
list.removeLastOccurrence(12);
System.out.println("Removed last occurrence"
+ " of '12' from the list");
// Displaying the modified LinkedList
System.out.println("LinkedList: "
+ list);
}
}
输出:
LinkedList: [12, 280, 12, 1050, 12]
Removed last occurrence of '12' from the list
LinkedList: [12, 280, 12, 1050]