List三种遍历集合方式

package com.czie.iot1913.lps.List;

/**
* @author 1944900433@qq.com
* @date 2022-03-17 14:05
*/
public class Student {
private String name;
private int age;

public Student() {
}

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}


package com.czie.iot1913.lps.List;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* @author 1944900433@qq.com
* @date 2022-03-17 17:29
*/
public class StudentListTest {
public static void main(String[] args) {
Student s1 = new Student("刘品水",21);
Student s2 = new Student("刘吕水",22);
Student s3 = new Student("刘口水",23);
List<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
//增强for遍历
for (Student s01:list){
System.out.println(s01.getName()+","+s01.getAge());
}
System.out.println("=======");
//Iterator遍历
Iterator<Student> it = list.iterator();
while (it.hasNext()){
Student s02=it.next();
System.out.println(s02.getName()+","+s02.getAge());
}
System.out.println("=======");
//for循环遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName()+","+list.get(i).getAge());
}
  System.out.println("===============");
  LinkedList<Object> linkedlist = new LinkedList<>();
  linkedlist.add("hello");
  linkedlist.add("java");
  linkedlist.add("mysql");
  for (Object c:linkedlist){
   System.out.println(c);
  }
  System.out.println("======");
  Iterator<Object> ite = linkedlist.iterator();
  while (ite.hasNext()){
   Object s01 = ite.next();
   System.out.println(s01);
  }
  System.out.println("=======");
  for (int i = 0; i < linkedlist.size(); i++) {
   Object o = linkedlist.get(i);
   System.out.println(o);
  
  }
    }
}
posted @ 2022-03-17 17:46  刘品水  阅读(71)  评论(0编辑  收藏  举报