java:ArrayList循环遍历的俩种方法使用 ArrayList取出第i个值

时间:2020-12-27 19:12:26

package collection;
import java.util.*;
public class NewArrayList {
 public static void main(String[] args) {
  List<Student> students = new ArrayList<Student>();
  for (int i = 0; i < 6; i++) {
   students.add(new Student("Happy"+i,"male"+i,20+i));
  }
  print(students);
  print2(students);
 }
 
 //循环遍历①for
 public static void print(List<Student> newList){
  System.out.println("总数据:"+newList.size());
  Student student;
  for (int i = 0; i < newList.size(); i++) {
   student = (Student)newList.get(i);
   System.out.println(student.toString());
  }
 }
 //循环遍历①Iterator
 public static void print2(List<Student> newList){
  System.out.println("总数据:"+newList.size());
  Iterator<Student> iterator = newList.iterator();
  Student student;
  while (iterator.hasNext()){
   student = (Student)iterator.next();
   System.out.println(student.toString());
  }
 }
 
}

 

 

 

 

用List的成员函数get(int index)
index表示要取的元素的下标(从0开始)
例如:你想取第一个元素"201";
List grouplist=this.getGroupList();
String s =(String)grouplist.get(0);
此时s="201";
如果要循环输出:
for(int i=0;i<grouplist.size();i++)
System.out.println(grouplist.get(i));