public class Student { String name; int age; public Student(int age,String name){ this.name=name; this.age=age; } }
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Listtest {
/**
* 用于存放学生信息的容器(List列表)
*/
public List testList;
public Listtest(){
this.testList=new ArrayList();
}
/**
* 添加学生信息
*/
public void testAdd(){
//判断列表是否为空
System.out.println("判断是否为空:"+testList.isEmpty());
Student stu1=new Student(20,"小明");
testList.add(stu1);
Student tem1=(Student) testList.get(0);
System.out.println("添加了学生:"+tem1.age+":"+tem1.name);
Student stu2=new Student(18, "邹邹");
testList.add(stu2);
Student tem2=(Student) testList.get(1);
System.out.println("添加了学生:"+tem2.age+":"+tem2.name);
Student stu3=new Student(19,"啊牛哥");
testList.add(stu3);
Student tem3=(Student) testList.get(2);
System.out.println("添加了学生:"+tem3.age+":"+tem3.name);
testList.add(null);
testList.add(stu2);
}
/**
* 遍历输出
* 方法1
* @param args
*/
public void testGet(){
int size=testList.size();
System.out.println("有如下学生:");
for(int i=0;i<size;i++){
Student stu=(Student) testList.get(i);
System.out.println(stu.age+":"+stu.name);
}
}
/**
* 遍历输出 方法2 迭代器Iterator
* @param args
*/
public void testIterator(){
//调用方法获取列表迭代器
Iterator i1=testList.iterator();
System.out.println("使用迭代器遍历!");
while(i1.hasNext()){//判断是否还有数据
Student stu=(Student) i1.next();
System.out.println(stu.age+":"+stu.name);
}
}
/**
* 通过for each 方法遍历
* @param args
*/
public void testForEach(){
System.out.println("有如下学生(for each)");
for(Object ob:testList){
Student stu=(Student) ob;
System.out.println(stu.age+":"+stu.name);
}
}
//获取列表中的个数
public void testSize(){
System.out.println("列表的长度为:"+testList.size());
}
/**
* 删除指定索引处的对象
* @param args
*/
public void testRemove() {
if(testList.contains(null)){
int i=testList.indexOf(null);
testList.remove(i);
}
}
public static void main(String[] args) {
Listtest l1=new Listtest();
l1.testAdd();
l1.testGet();
l1.testIterator();
l1.testForEach();
l1.testSize();
l1.testRemove();
l1.testSize();
}
}
运行结果如下:
判断是否为空:true
添加了学生:20:小明
添加了学生:18:邹邹
添加了学生:19:啊牛哥
有如下学生:
20:小明
18:邹邹
19:啊牛哥
Exception in thread "main" java.lang.NullPointerException
at collection.Listtest.testGet(Listtest.java:53)
at collection.Listtest.main(Listtest.java:98)
相关分类