List、Set集合遍历方式

来源:互联网 发布:java编写99乘法表 编辑:程序博客网 时间:2024/05/18 01:02
public class Test {

 
 public static void main(String[] args) {
  //范型  避免因类型强转而产生的错误

  List<Student> list = new ArrayList<Student>();
  list.add(new Student(1,"dfd"));
  list.add(new Student(4,"hfg"));
 list.add(new Student(2,"dsf"));
 list.add(new Student(8,"fgfg"));
 

第一种方式:for循环 
  //遍历List集合里的内容 只对List有效 因为List是有序的集合
  for(int i = 0;i<list.size();i++){
   System.out.println(list.get(i).id+"  "+list.get(i).name);
  }
  

第二种方式:iterator迭代器
  //迭代器方式 弱点是只能从头到尾 兼容性最好 适合于Collection集合
  Iterator<Student> it = list.iterator();
  
  while(it.hasNext()){//hasNext()判断有没有下一个元素
   Student st = it.next();
   System.out.println(st.id+"  "+st.name);
  }
  
  

第三种方式:for each
  //for each 方式本质还是迭代器 每循环一次 放的就是当前对象的地址 适合List Set Map
  //只能在JK1.5以上使用 兼容性不好 Set最好用这种 
  for(Student t:list){
   System.out.println(t.id+"  "+t.name);
  }
  

遍历Set集合和List的方式一样 不过不能使用for 循环来遍历Set集合 因为Set集合中没有get()方法
 

原创粉丝点击