java学习笔记(十三)

一、集合的迭代(遍历)(模仿了数鸡蛋的方式)

1.java接口Iterator(迭代器)描述了逐一遍历的方法

2.Iterator描述了一个顺序结构,并且有一个游标的概念,游标默认在第一个元素之前,调用方法hasNext()可以检查游标是否有下一个元素,使用next()方法移动游标,并且返回当前游标指向的元素,这两个方法经常与while循环组成模块化结构,用来遍历集合内容,是常见的标准结构

3.凡是对集合的遍历都应采用Interator接口实现,编程中十分常见

4.集合在迭代期间不能调用集合的更新方法add(),remove,set等

5.如果需要迭代时候删除集合内容,可以调用迭代器的删除方法,ite.remove()删除当前元素

实例:

public static void main(String[] args) {
	//	List<String>eggs=new ArrayList<String>();
		List eggs=new MyArrayList();
		eggs.add("egg1");
		eggs.add("egg2");
		eggs.add("egg3");
		eggs.add("egg4");
		eggs.add("egg5");
		eggs.add("egg6");
		Iterator<String> ite=eggs.iterator();
		int sum=0;
		while(ite.hasNext()){//hasNext,next基本都用while或者for循环
			String e=ite.next();
			System.out.println(e);
			sum++;
		}
		System.out.println(sum);
	}
public static void main(String[] args) {
		Set<String> set=new HashSet<String>();
		set.add("A");
		set.add("B");
		set.add("C");
		set.add("D");
		set.add("A");
		System.out.println(set.size());//重复的元素加不进去
		for(Iterator i=set.iterator();i.hasNext();){
			String s=(String)i.next();
			System.out.println(s);
		}
	}

二、泛型

实例:

public class GmDemo {
	public static void main(String[] args) {
		Shop<Food> foodShop=
				new Shop<Food>(new Food[]{new Food()});
		Shop<Pet> petShop=
				new Shop<Pet>(new Pet[]{new Pet()});
		
		Food f=foodShop.buy(0);
		Pet p=petShop.buy(0);
		
		System.out.println(f);
		System.out.println(p);
	}
}
class Food{
	public String toString(){
		return "食品";
	}
}
class Pet{
	public String toString(){
		return "动物";
	}
}
class Shop<P>{
	P[] products;
	public Shop(P[] products){
		this.products=products;
	}
	P buy(int i){
		return products[i];
	}
}
一个对象内部包裹的数据类型

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值