java.util.LinkedList.removeFirstOccurrence() se utiliza para eliminar la primera aparición del elemento especificado de la lista. Si el elemento especificado no aparece, la lista permanece sin cambios.
Sintaxis :
LinkedListObject.removeFirstOccurrence(Object element)
Parámetros: el método toma un elemento de parámetro que se eliminará de la lista. El tipo Objeto debe ser el mismo que los elementos de la lista.
Valor de retorno: el método devuelve True booleano si la lista contiene el elemento especificado y se elimina; de lo contrario, devuelve false.
Los siguientes programas ilustran el método removeFirstOccurrence():
Programa 1:
java
// Java code to demonstrate removeFirstOccurrence() method import java.util.LinkedList; public class GfG { // Main method public static void main(String[] args) { // Creating a LinkedList object LinkedList<String> list = new LinkedList<String>(); // Adding an element at the last list.addLast("one"); // Adding an element at the last list.addLast("two"); // Adding an element at the last list.addLast("three"); // Adding an element at the last list.addLast("one"); System.out.print("List before removing the "+ "first Occurrence of \"one\" : "); // Printing the list System.out.println(list); // Removing first occurrence of one. boolean returnValue = list.removeFirstOccurrence("one"); // Printing the returned value System.out.println("Returned Value : " + returnValue); System.out.print("List after removing the"+ " first Occurrence of \"one\" : "); // Printing the list System.out.println(list); } }
Producción:
List before removing the first Occurrence of "one" : [one, two, three, one] Returned Value : true List after removing the first Occurrence of "one" : [two, three, one]
Programa 2:
Java
// Java code to demonstrate removeFirstOccurrence method in LinkedList import java.util.LinkedList; public class GfG { // Main method public static void main(String[] args) { // Creating a LinkedList object LinkedList<Integer> list = new LinkedList<Integer>(); // Adding an element at the last list.addLast(10); // Adding an element at the last list.addLast(20); // Adding an element at the last list.addLast(30); // Adding an element at the last list.addLast(10); System.out.print("List before removing the"+ " first Occurrence of \"10\" : "); // Printing the list System.out.println(list); // Removing first occurrence of one. boolean returnValue = list.removeFirstOccurrence(10); // Printing the returned value System.out.println("Returned Value : " + returnValue); System.out.print("List after removing the"+ " first Occurrence of \"10\" : "); // Printing the list System.out.println(list); } }
Producción:
List before removing the first Occurrence of "10" : [10, 20, 30, 10] Returned Value : true List after removing the first Occurrence of "10" : [20, 30, 10]