Adding a List collection to the List inserting an object reports a null pointer exception

One task I did today was to append the List collection to the List collection, but there was a problem with a null pointer exception:

Look at the code:

@Override
    public List<List<Item>> queryHotItem() {
        //先去查找对应的itemId
        List<UserHot> userHotList=itemHotMapper.queryHotItem();
        List<List<Item>> HotItemList = null;
        
//        List<Item> HotItemList=itemHotMapper.queryHotItem();
        //然后根据ItemId来查找对应的物品信息
        for(int i=0;i<userHotList.size();i++){
            String itemId=userHotList.get(i).getItemId();
            List<Item> test=itemHotMapper.queryItemInfo(itemId);
            System.out.println(test);
            HotItemList.add(test);
        }
        System.out.println(HotItemList);
        return HotItemList;
    }

Reported a null pointer, then checked Baidu and found

 Cannot be used when creating a List collection:

If you just use List<UserAndTest> list1 = null; There is just a reference in the stack but no memory space is allocated. If I add objects directly to the List at this time, I will directly store things in the reference point, because there is no allocation Memory, so it will report a null pointer exception, so you need to write:

List<List<Item>> HotItemList = new ArrayList<>();

 

Guess you like

Origin blog.csdn.net/qq_30631063/article/details/107936616