栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

常见java空指针异常NPE

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

常见java空指针异常NPE

总述

NPE(NullPointerException)

方法的返回值可以为null,不强制返回空集合,或者空对象等,必须添加注释充分说明什么情况下会返回 null 值。防止NPE是调用者的责任:返回空集合或空对象仍然可能在“远程调用失败、序列化失败、运行时异常”时返回null防止NPE:包装类为null,集合元素为null,级联调用,数据库查询结果,远程调用返回对象,session中对象来自阿里巴巴java开发手册泰山版 创建数组对象,元素为null

public class BucketSort {
	private static class Node {
        private int key;
        private int next;

        public Node() {
        }

        public Node(int key, int next) {
            this.key = key;
            this.next = next;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getNext() {
            return next;
        }

        public void setNext(int next) {
            this.next = next;
        }
    }

	public static void main(String[] args) {
		// 创建数组对象,只是分配了空间
		Node[] nodes = new Node[n];
        for (int i = 0; i < n; i++) {
        	// 抛出 NPE
            nodes[i].key = r[i];
            nodes[i].next = i + 1;
        }
	}
}

包装类为null,自动拆箱报错
	private static int testIntegerNull() {
        Integer integer = null;
        return integer;
    }
    
    public static void main(String[] args) {
            testIntegerNull();
    }
集合元素为null
	private static void testCollectionElementNull() {
        String str = null;
        List list = new ArrayList<>();
        list.add(str);

        if (!list.isEmpty()) {
            System.out.println(list.get(0).equals("xcrj"));
        }
    }
	
	public static void main(String[] args) {
        testCollectionElementNull();
    }
对象级联调用
// 建议使用Optional处理
obj.getA().getB().getC()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782080.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号