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; } }
相关文章推荐
- 用 for/in 在 Java 5.0 中增强循环
- 黑马程序员-jdk1.5新特性--For循环增强
- 这是JAVA1.5 增强的for 循环的新特性
- 读书笔记之 将所有增强for语句的循环变量声明为final类型
- 增强for循环用法
- [Java学习笔记]增强for循环和Map的两种读取方式
- 增强的for循环语句
- 【黑马程序员】张孝祥Java高新技术_静态导入、可变参数、增强for循环
- 清华大学计算中心培训部-技术分享:Java基础教程:增强的for循环
- 用 for/in 在 Java 5.0 中增强循环
- Java中的增强for循环与iterator
- 黑马程序员_Java高新技术_增强for循环
- Java高新技术【1】 (静态导入-可变参数-增强for循环-基本数据类型的自动拆箱与装箱)
- 黑马程序员--基础--第一篇--JDK5.0新特性泛型 静态倒入 自动拆装箱 不定项参数 增强for如循环 枚举
- Java 增强for循环原理
- JDK1.5 新特性-增强FOR循环
- 增强for 循环
- Java增强的for循环和普通for循环对比
- 黑马程序员 十四、Eclipse 的使用、增强 for 循环、自动拆箱与装箱等
- 增强for循环用法