http://www.yee4.com/blog/187.html/3
http://blog.csdn.net/vozon/article/details/5458370
public class Coll {
// Collection<String> coll=,,,
// 迭代器写法
// Iterator<String> iter = coll.iterator();
// while(iter.hashNext()){
// String element = iter.next();
// do something with element
// }
// for each写法 是迭代器优雅的缩写方式
// for(String element:coll){
// do something with element
// }
// 两种写法可以表示同样的循环操作
public static void main(String[] args) {
HashSet<String> hashset = new HashSet<String>();
HashMap<Integer,Cat> hashmap = new HashMap<Integer,Cat>();
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
hashset.add("1");
hashset.add("2");
hashset.add("3");
Cat c1 = new Cat("cat1",10);
Cat c2 = new Cat("cat2",20);
Cat c3 = new Cat("cat3",30);
hashmap.put(10, c1);
hashmap.put(20, c2);
hashmap.put(30, c3);
//hashset遍历方法1
for(String Str :hashset){
System.out.print(Str+" ");
}
System.out.println();
//hashset遍历方法2
Iterator<String> it = hashset.iterator();
while(it.hasNext())//hashNext判断是否还有下一个元素
{
System.out.print(it.next()+" ");//调用next后,索引往下移动一个数据
}
System.out.println();
hashMap遍历方法1 匿名内部类Map.Entry
for(Map.Entry<Integer , Cat> entry : hashmap.entrySet()){
System.out.println("Key="+entry.getKey()+" value="+entry.getValue().toString());
}
//hashMap遍历方法2 用keySet遍历
Iterator it2=hashmap.keySet().iterator();//这是取得键对象
while(it2.hasNext())
{
System.out.println( "key的值是: "+(it2.next())); //获得键所对应的值。
}
//hashMap遍历方法3 用entrySet遍历
Iterator it3 = hashmap.entrySet().iterator();
while(it3.hasNext()){
Entry entry=(Entry)it3.next();
Object key=entry.getKey();
Object value=entry.getValue();
System.out.println("key="+key+" value="+value);
}
//ArrayList 遍历方法1
Iterator it4 = list.iterator();
while(it4.hasNext())
{
System.out.print(it4.next()+" ");
}
System.out.println();
//ArrayList 遍历方法2
for(int i=0;i<list.size();i++)//size方法返回ArrayList中元素的个数
{
System.out.print(list.get(i)+" ");//get方法得到某个位置的元素
}
}
}
class Cat{
String name;
int year;
public Cat(String name, int year) {
super();
this.name = name;
this.year = year;
}
public String toString(){
return "[name=" + name + ", year=" + year + "]";
}
}