增强for循环格式:
for(数据类型 变量名 : 遍历的目标){
//数据类型 变量名:声明一个变量用来接收遍历目标遍历后的元素
}
增强for循环的作用:
简化迭代器的书写格式。(注意:增强for循环的底层还是使用了迭代器遍历。)
增强for循环的适用范围: 如果是实现了Iterable接口的对象或者是数组对象都可以使用增强for循环。
增强for循环的缺点:增强for循环和iterator遍历的效果是一样的,增强for循环的内部也是调用iteratoer实现,但是增强for循环不能在动态的删除集合内容、不能获取下标等。
eg:
Collection col = new ArrayList();
col.add(new book("三国","施",10));
col.add(new book("sss" , "盛",34.1));
Iterator iter = col.iterator();
//第一次遍历
while(iter.hasNext()) {
//String str = (String)iter.next();
Object obj = iter.next();
System.out.println(obj.toString());//重写toString方法
}
//第二次遍历,需要重置遍历器
for(Object book :col ) {
System.out.println(book);
}
//book类中的部分代码
class book{
private String name;
private String author;
private double price;
/*一定要重写toString方法,原本的toString方法是获取的地址
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
*/
public String toString() {
return "name---"+name+"author---"+author+"price---"+price;
}
public book(String name, String author, double price) {
super();
this.name = name;
this.author = author;
this.price = price;
}
扩展:equals方法重写
eg:
//原本的方法
public boolean equals(Object obj) {
return (this == obj);
}
//重写后的方法
public boolean equals(Object obj) {
if(this==obj) {
return true;
}
if(obj instanceof Circle) {
Circle order = (Circle)obj;
return this.name.equals(order.radius);
}
return false;
}