增强for循环
专门用来遍历数组和集合的。它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。
格式:
for(元素的数据类型 变量 : Collection集合or数组){
}
例子
public static void main(String[] args) {
//普通for
Collectioncol = new ArrayList();
col.add(new Person("熊大",22));
col.add(new Person("熊二",10));
col.add(new Person("吉吉国王",30));
ArrayList list = (ArrayList)col;
for(int i =0;i
System.out.println(list.get(i));
}
//增强for 没有下标
/*for(要遍历的数据类型 变量名:容器名){
}*/
for(Person p:col) {
System.out.println(p);
}
增强for循环和老式的for循环有什么区别?
遍历数组,集合时,如果仅为遍历,可以使用增强for,如果要对数组的元素进行操作,使用普通for循环可以通过下标操作。
泛型
泛型,用来灵活地将数据类型应用到不同的类、方法、接口当中。将数据类型作为参数进行传递。
优点
将运行时期的ClassCastException,转移到了编译时期变成了编译失败。
避免了类型强转的麻烦。泛型不进class文件
例子
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
list.add("oracle");
//list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
//集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
Iterator it = list.iterator();
while(it.hasNext()){
String str = it.next();
//当使用Iterator控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
System.out.println(str.length());
}
}