zoukankan      html  css  js  c++  java
  • NullPointerException-----开发中遇到的空指针异常

    1.使用CollectionUtils.isEmpty判断空集合

    public class TestIsEmpty {
        static class Person{}
        static class Girl extends Person{}
        
        public static void main(String[] args) {
            List<Integer> first = new ArrayList<>();
            List<Integer> second = null;
            List<Person> boy = new ArrayList<>();
            boy.add(new Girl());
            System.out.println(CollectionUtils.isEmpty(first));//true
            System.out.println(CollectionUtils.isEmpty(first));//true
            System.out.println(CollectionUtils.isEmpty(first));//false
    
            System.out.println(first==null);//false
            System.out.println(second==null);//true
            System.out.println(boy==null);//false
    
            System.out.println(first.size()); //size=0
            System.out.println(second.size());// NullPointerException
            System.out.println(boy.size());  //size=1


    System.out.println(first.isEmpty()); //true
    System.out.println(second.isEmpty()); //NullPointerException
    System.out.println(boy.isEmpty()); //false

    所以:
    isEmpty() 或者(list.size() == 0)用于判断List内容是否为空,即表里一个元素也没有
    但是使用isEmpty()和size()的前提是,list是一个空集合,而不是null,
    所以为了避免异常,建议在使用或赋值list集合之前,做一次空集合创建处理,进行内存空间分配,即: List list2 = new ArrayList()
    判断不为空的情况: list!=null && !list.isEmpty()

    } }

    二 .容易出现空指针的地方

    1.实体类里定义的集合

    public class Org {
        private Long id;
        private String title;
        private Long parent;
        private List<User> list;
    
        public Long getId() {return id;}
        public void setId(Long id) {this.id = id;}
        public String getTitle() {return title;}
        public void setTitle(String title) {this.title = title;}
        public Long getParent() {return parent;}
        public void setParent(Long parent) {this.parent = parent;}
        public List<User> getList() {
            if(list==null){
                list=new ArrayList<>();  //这里最好对这个集合处理一下,防止报空指针
            }
            return list;
        }
    
        public void setList(List<User> list) {
            this.list = list;
        }
    }

    2.自己定义的集合接收数据库查询的数据

    如:List<Org> users=userService.getAll();
          如果查询结果为空,users.size=0.users是一个空集合,但不是空
          使用前最好判断一下是不是为空
  • 相关阅读:
    7.29随堂笔记
    LeetCode77. 组合
    347. 前 K 个高频元素
    LeetCode239. 滑动窗口最大值
    C++_数字字符串互相转换
    LeetCode150. 逆波兰表达式求值
    LeetCode1047. 删除字符串中的所有相邻重复项
    LeetCode20. 有效的括号
    Leetcode225. 用队列实现栈 && LeetCode232. 用栈实现队列
    leetCode5663. 找出第 K 大的异或坐标值
  • 原文地址:https://www.cnblogs.com/inspred/p/7646579.html
Copyright © 2011-2022 走看看