集合常見的幾種遍歷方式

2021-09-14 03:03:13 字數 2483 閱讀 3189

建立dog類用於存入集合遍歷

public

class

dogpublic string getname()

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

//重寫tostring方法

@override

public string tostring()

}

list泛型集合迭代

list

list=

newarraylist

(); list.

add(

newdog

("小胡",8

)); list.

add(

newdog

("小花",2

)); list.

add(

newdog

("小花",2

)); iterator

iterlist=list.

iterator()

;while

(iterlist.

hasnext()

)

list的增強型for迴圈遍歷

for

(dog dog:list)

list通過下標遍歷for迴圈遍歷

for

(int i=

0;isize()

;i++)~

~~**set集合泛型迭代*

* set

set =

newhashset

(); set.

add(

newdog

("小胡",8

)); set.

add(

newdog

("小花",2

)); set.

add(

newdog

("小美",8

)); iterator

iterset=set.

iterator()

;while

(iterset.

hasnext()

)

set增強型for迴圈遍歷

for

(dog dogfor:set)

map的泛型迭代->map.entry

map

map=

newhashmap

(); map.

put(1,

newdog

("小胡",8

)); map.

put(2,

newdog

("小花",2

)); map.

put(2,

newdog

("小小",8

)); map.

put(2,

newdog

("小花",2

));

遍歷map的泛型方法–迭代器–:方式一(迭代器裡的泛型也可以省略)

iterator

> itr=map.

entryset()

.iterator()

;while

(itr.

hasnext()

)

map的泛型迭代->通過獲取key的set集合來獲取值

iterator

itr3=map.

keyset()

.iterator()

;while

(itr3.

hasnext()

)

通過獲取值存入集合中

iterator

itr4=map.

values()

.iterator()

;while

(itr4.

hasnext()

)

增強型for迴圈遍歷鍵值對

for

(map.entry

entry:map.

entryset()

)

希望對你們有幫助…

集合的幾種遍歷方式

listlist new arraylist list.add aaa list.add bbb list.add ccc 普通for迴圈 for int i 0 i list.size i 增強for迴圈 for string string list 使用迭代器 iteratorite list....

遍歷集合的幾種方式

list list newarraylist 1 集合的迭代器遍歷。iterator it list.iterator while it.hasnext 2 增強for迴圈。for string ele list 3 jdk1.8後的新技術 lambda表示式。list.foreach e syst...

幾種集合遍歷方式的效率對比

double time0 system currenttimemillis treeset.foreach o system out println o double time1 system currenttimemillis for person o treeset double time2 s...