在Java中的LinkedList中搜索特定元素
可以使用java.util.LinkedList.indexOf()方法在LinkedList中搜索特定元素。此方法返回所搜索元素的首次出现的索引。如果该元素在LinkedList中不可用,则此方法返回-1。
演示此的程序如下所示-
示例
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("A");
l.add("B");
l.add("C");
l.add("D");
l.add("E");
System.out.println("The index of element B in LinkedList is: " + l.indexOf("B"));
System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z"));
}
}输出结果
The index of element B in LinkedList is: 1 The index of element Z in LinkedList is: -1
现在让我们了解上面的程序。
LinkedListl被创建。然后,LinkedList.add()用于将元素添加到LinkedList。LinkedList.indexOf()返回显示的第一次出现的“B”和“Z”的索引。演示这的代码片段如下-
LinkedList<String> l = new LinkedList<String>();
l.add("A");
l.add("B");
l.add("C");
l.add("D");
l.add("E");
System.out.println("The index of element B in LinkedList is: " + l.indexOf("B"));
System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z"));热门推荐
3 足球队祝福语简短
10 除夕的拜年祝福语简短
11 祖国生日祝福语简短英文
12 离别简短的祝福语大全
13 过节文案成语祝福语简短
14 舅妈生日红包祝福语简短
15 姐姐女儿结婚祝福语简短
16 六一婚礼文案祝福语简短
17 叔叔生日祝福语简短励志
18 婶婶生日贺词简短祝福语