您的位置:首页 > 其它

Collection(三) 增强for循环

2012-02-21 10:22 99 查看
import java.util.ArrayList;
import java.util.Collection;
//增强for循环,适用于数组或容器的简单遍历或内容的读取。
public class EnhanceFor {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
for(int i:arr){
System.out.println(i);
}
Collection c = new ArrayList();
c.add(new Name("fi","li"));
c.add(new Name("gi","oi"));
c.add(new Name("ui","pi"));
for(Object obj:c){
System.out.println(obj);
}
}
}


Name类:

public class Name {
private String firstName;
private String lastName;
public Name(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
//当使用contains,removes时,需要在本类中重写equals方法
public boolean equals(Object o){
if(o instanceof Name){
Name name = (Name)o;
return (firstName.equals(name.firstName))&&(lastName.equals(name.lastName));
}
return super.equals(o);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
//重写equals应该重写hashCode方法,两对象相互equals他们的hashCode必须相等;
//当一个对象作为索引(Map里的键)时要用hashCode
public int hashCode(){
return firstName.hashCode();
}
public String toString(){
return firstName+","+lastName;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: