Java中遍历集合Set的几种方法

一、迭代遍历

Set<L> set = new HashSet<L>();
Iterator<String> it = set.iterator(); 
while (it.hasNext()) {
	L temp = it.next();
	/*
	*操作……
	*/
} 

二、for循环遍历

for (L temp : set) {
/*
*操作……
*/
}

优点还体现在泛型 假如 set中存放的是Object

Set<Object> set = new HashSet<Object>();
for循环遍历:
for (Object obj : set) {
	if(obj instanceof Integer){
		int aa= (Integer)obj;
	} else if ( obj instanceof String ) {
               String aa = (String)obj
           }
              ........
}

猜你喜欢

转载自blog.csdn.net/weixin_43915689/article/details/89093325