Arraylist HashMap HashSet 遍历

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 + "]";
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值