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

Java Example – Reversing a Collection

Java Example – Reversing a Collection

Java Examples Java Examples

The following example demonstrates how to use the listIterator() method of the Collection and ListIterator classes and the collection.reverse() method to reverse the elements in the collection:

Main.java File

import

java

.

util

.

ArrayList

;

import

java

.

util

.

Collections

;

import

java

.

util

.

List

;

import

java

.

util

.

ListIterator

;

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

String

[

]

coins

=

{

"

A

"

,

"

B

"

,

"

C

"

,

"

D

"

,

"

E

"

}

;

List

l

=

new

ArrayList

(

)

;

for

(

int

i

=

0

;

i

<

coins

.

length

;

i

++

)

l

.

add

(

coins

[

i

]

)

;

ListIterator

liter

=

l

.

listIterator

(

)

;

System

.

out

.

println

(

"

Before reversal

"

)

;

while

(

liter

.

hasNext

(

)

)

System

.

out

.

println

(

liter

.

next

(

)

)

;

Collections

.

reverse

(

l

)

;

liter

=

l

.

listIterator

(

)

;

System

.

out

.

println

(

"

After reversal

"

)

;

while

(

liter

.

hasNext

(

)

)

System

.

out

.

println

(

liter

.

next

(

)

)

;

}

}

The output of the above code is:



反转前

A

B

C

D

E

反转后

E

D

C

B

A

Java Examples Java Examples