java 增強(qiáng)for循環(huán)
增強(qiáng)for循環(huán):可以用來遍歷單列集合或者數(shù)組,底層采用的是迭代器
格式:
for(數(shù)組或者集合中元素的類型 變量名 : 遍歷的數(shù)組/單列集合){
變量名代表的是數(shù)組或者結(jié)合中的元素
}
好處:簡化了單列集合和數(shù)組的遍歷
缺點:沒用索引,遍歷的目標(biāo)不能為空
public class Demo {
public static void main(String[] args) {
int[] arr = {1,5,6,3,2,8};
for(int i : arr){
System.out.println(i);
}
System.out.println("=============");
Collection<String> c = new ArrayList<>();
c.add("張飛");
c.add("劉備");
c.add("關(guān)羽");
for(String s : c){
System.out.println(s);
}
}
}
迭代器是什么呢
public class Demo {
public static void main(String[] args) {
//創(chuàng)建集合
Collection<String> c = new ArrayList<>();
//添加集合
c.add("張飛");
c.add("劉備");
c.add("關(guān)羽");
c.add("大喬");
//遍歷集合,創(chuàng)建迭代器
Iterator<String> it = c.iterator();
//取下一個元素
/*String s1 = it.next();
System.out.println(s1);
String s2 = it.next();
System.out.println(s2);*/
//使用迭代器,遍歷,改變集合也要使用迭代器,否則會拋出異常
while (it.hasNext()) {
String s = it.next();
if (s.equals("大喬")) {
it.remove();
}
}
System.out.println(c);
}
}
學(xué)的不是技術(shù),更是夢想?。?!文章來源地址http://www.zghlxwxcb.cn/news/detail-621733.html
文章來源:http://www.zghlxwxcb.cn/news/detail-621733.html
到了這里,關(guān)于java 增強(qiáng)for循環(huán)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!