null和空列表有什么区别? [英] What is difference between null and empty list?

查看:158
本文介绍了null和空列表有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        List<Map<String, Object>> pcList = null;
        Map<String, Object> pcMap = new HashMap<String, Object>();
        ComputerConfigurations tempPC = null;

        if (historyList != null) {
            Iterator<ComputerConfigurations> iterator = historyList.iterator();
            while (iterator.hasNext()) {
                tempPC = (ComputerConfigurations) iterator.next();
                pcMap.put(tempPC.getEnvironment(), tempPC);
                pcList.add((Map<String, Object>) pcMap);
            }
        }

我在<$ c $上获得空指针异常c> pcList.add((Map< String,Object>)pcMap); line。 [Servlet Error] - :java.lang.NullPointerException 。有什么建议吗?

I am getting null pointer exception on pcList.add((Map<String, Object>)pcMap); line. [Servlet Error]-: java.lang.NullPointerException . Any suggestion ?

推荐答案

在Java中,只要向它们添加内容,集合就不会神奇地存在。您必须先创建一个集合来初始化 pcList

In Java, collections won't magically spring into existence just by adding something to them. You have to initialize pcList by creating an empty collection first:

List<Map<String, Object>> pcList = new ArrayList<>();

空集合与 null 。空集合实际上是一个集合,但它还没有任何元素。 null 表示根本不存在任何集合。

An empty collection isn't the same as null. An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.

请注意,对象的类型不能为列出,因为那是一个接口;因此,你必须告诉Java你真正需要什么样的 List (例如 ArrayList ,就像我一样如上所示,或 LinkedList ,或实现 List 的其他类。

Note that an object can't be of type List, because that's an interface; therefore, you have to tell Java what kind of List you really want (such as an ArrayList, as I've shown above, or a LinkedList, or some other class that implements List).

这篇关于null和空列表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆