ArrayList的addAll方法使用注意

来源:互联网 发布:淘宝宽屏 编辑:程序博客网 时间:2024/05/18 04:57
<span style="font-size:18px;">package com.robot.test;import java.util.ArrayList;public class TestCode {public static void main(String[] args) {ArrayList<Student> stuList = new ArrayList<Student>();Student s1 = new Student(12, "jack");Student s2 = new Student(23, "Ann");Student s3 = new Student(76, "Mike");stuList.add(s1);stuList.add(s2);stuList.add(s3);ArrayList<Student> stuList2 = new ArrayList<Student>();stuList.addAll(stuList2); // 正确ArrayList<Student> stuList3 = null;stuList.addAll(stuList3); // 报错,由于stuList3为null指针}}</span>
<span style="font-size:18px;">package com.robot.test;public class Student{<span style="white-space:pre"></span>public int age;<span style="white-space:pre"></span>public String name;<span style="white-space:pre"></span>Student(int age, String name) {<span style="white-space:pre"></span>this.age = age;<span style="white-space:pre"></span>this.name = name;<span style="white-space:pre"></span>}}</span>

总结:在使用ArrayList的addAll()方法的时候一定要进行非null的判断。

0 0
原创粉丝点击