Java LinkedList removeLastOccurrence()方法及示例

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<String> list
            = new LinkedList<String>();
 
        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]

示例2

// Java program to demonstrate removeLastOccurrence()
// method of LinkedList
 
import java.util.*;
 
class LinkedListDemo {
    public static void main(String[] args)
    {
        LinkedList<Integer>
            list = new LinkedList<Integer>();
 
        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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程