一、集合的迭代(遍历)(模仿了数鸡蛋的方式)
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];
}
}
一个对象内部包裹的数据类型