本教程将演示如何在LinkedList上执行各种操作,它们分别如下 –
- 将元素添加到LinedList中。
- 从LinkedList中删除元素。
- 搜索LinkedList中的元素。
- 检查LinkedList的大小。
- 检查LinkedList中是否存在元素。
- 从LinkedList中删除所有元素。
文件:LinkedListExample.java –
package com.yiibai.tutorial; import java.util.LinkedList; import java.util.List; public class LinkedListExample { public static void main(String[] args) { List<String> list=new LinkedList<>(); /*Adding elements into the linked list*/ list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); list.add("Five"); System.out.println("Elements in linked list:"+list); /*Removing an element from the linked list*/ String removedEle=list.remove(0); // Remove the first element System.out.println("Element revoved:"+removedEle); System.out.println("Elements in list after removal:"+list); /*Retrieving an element in the linked list*/ String element=list.get(1); // Get second element System.out.println("Element at second position:"+element); /*Print size of List*/ System.out.println("Number of elements:"+list.size()); /*Check if an element exist in the linked list*/ System.out.println("Element exist:"+list.contains("Five")); /*Finding the index of an element*/ System.out.println("Index of 'Four' is :"+list.indexOf("Four")); /*Removing all elements from the linked list*/ list.clear(); System.out.println("Elements in linked list:"+list); } }
执行上面示例代码,得到以下结果 –
Elements in list:[One Two Three Four Five] Element revoved:One Elements in list after removal:[Two Three Four Five] Element at second position:Three Number of elements:4 Element exist:true Index of 'Four' is :2 Elements in list:[]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264151.html