Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Searching for Elements in a LinkedList

Java Example – Searching for Elements in a LinkedList

Java Examples Java Examples

The following example demonstrates using the linkedlistname.indexOf(element) and linkedlistname.lastIndexOf(elementname) methods to get the first and last occurrence positions of an element in the linked list:

Main.java File

import

java

.

util

.

LinkedList

;

public

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

LinkedList

lList

=

new

LinkedList

(

)

;

lList

.

add

(

"

1

"

)

;

lList

.

add

(

"

2

"

)

;

lList

.

add

(

"

3

"

)

;

lList

.

add

(

"

4

"

)

;

lList

.

add

(

"

5

"

)

;

lList

.

add

(

"

2

"

)

;

System

.

out

.

println

(

"

The first occurrence position of element 2:

"

lList

.

indexOf

(

"

2

"

)

)

;

System

.

out

.

println

(

"

The last occurrence position of element 2:

"

lList

.

lastIndexOf

(

"

2

"

)

)

;

}

}

The output of the above code is:



元素 2 第一次出现的位置:1

元素 2 最后一次出现的位置:5

Java Examples Java Examples