Java:HashMap工作,LinkedHashMap获取Null Pointer Exception

时间:2013-03-20 16:30:00

标签: java nullpointerexception hashmap

我几周前开始学习Java,来自PHP而没有其他先前的语言背景。我习惯只使用array()...

当我将我的类从HashMap更改为LinkedHashMap时,我得到一个空指针异常,

使用JDK 1.6

类LinkedHashMap - 来自Oracle Oracle JDK 1.6 Reference

  

此类提供所有可选的Map操作,并允许null元素。与HashMap一样,它为基本操作(添加,包含和删除)提供了恒定时间性能,假设哈希函数在桶之间正确地分散元素。由于维护链表的额外费用,性能可能略低于HashMap的性能,但有一个例外:对LinkedHashMap的集合视图进行迭代需要与映射大小成比例的时间,无论其容量如何。对HashMap的迭代可能更昂贵,需要与其容量成比例的时间。

不起作用

@Component("blMenu")
public class MenuProcessor extends AbstractModelVariableModifierProcessor {
public  List<Category> topLevelCategories;
public  LinkedHashMap<Category, LinkedHashMap<Integer, List<Category>>> navigationMenu = new LinkedHashMap<Category, LinkedHashMap<Integer, List<Category>>>();
public List<Category> Categories;
public int chunkSize = 5;
public int subCategoriesSize;
public String resultVar;

/**
 * Sets the name of this processor to be used in Thymeleaf template
 */
public MenuProcessor() {
    super("menu");
}

@Override
public int getPrecedence() {
    return 10000;
}

@Override
protected void modifyModelAttributes(Arguments arguments, Element element) {
    CatalogService catalogService = ProcessorUtils.getCatalogService(arguments);

    resultVar = element.getAttributeValue("resultVar");
    String parentCategory = element.getAttributeValue("parentCategory");
    String unparsedMaxResults = element.getAttributeValue("maxResults");

    // TODO: Potentially write an algorithm that will pick the minimum depth category
    // instead of the first category in the list
    List<Category> categories = catalogService.findCategoriesByName(parentCategory);
    if (categories != null && categories.size() > 0) {
        // gets child categories in order ONLY if they are in the xref table and active
        List<Category> subcategories = categories.get(0).getChildCategories();
        if (subcategories != null && !subcategories.isEmpty()) {
            if (StringUtils.isNotEmpty(unparsedMaxResults)) {
                int maxResults = Integer.parseInt(unparsedMaxResults);
                if (subcategories.size() > maxResults) {
                    subcategories = subcategories.subList(0, maxResults);
                }
            }
        }
        topLevelCategories = subcategories;
        buildMenu(arguments, catalogService);
    }
}

public void buildMenu(Arguments arguments, CatalogService catalogService)
{
    LinkedHashMap<Integer, List<Category>> chunkSubs;

    for(Category topLvlCat : topLevelCategories)
    {

        Categories = catalogService.findCategoriesByName(topLvlCat.getName());
        List<Category> subCategories = Categories.get(0).getChildCategories();

        if(subCategories != null && !subCategories.isEmpty())
        {
            subCategoriesSize = subCategories.size();
            chunkSubs = chunkSubCategories(subCategories);
            navigationMenu.put(topLvlCat, chunkSubs);
        }
        else
        {
            navigationMenu.put(topLvlCat, null);
        }
    }
    addToModel(arguments, resultVar, navigationMenu);
}


public LinkedHashMap<Integer, List<Category>> chunkSubCategories(List<Category> subCategories)
{
    List<Category> chunkedCategories;
    LinkedHashMap<Integer, List<Category>> subCategoriesChunked = new LinkedHashMap<Integer, List<Category>>();

    int iLoop = 0;
    int start = 0;
    int end = chunkSize - 1;
    int catSize = subCategoriesSize-1;

    if(subCategoriesSize > 1){
    do
    {

        if(end < catSize)
        {
            chunkedCategories = subCategories.subList(start, end);
            subCategoriesChunked.put(iLoop, chunkedCategories);
        }
        else
        {
            end = end - (end-catSize);
            chunkedCategories = subCategories.subList(start, end);
            subCategoriesChunked.put(iLoop, chunkedCategories);
        }

        iLoop = iLoop + 5;
        start = start + chunkSize;
        end = end + chunkSize;

    }while(subCategoriesSize > iLoop);
    }
    return subCategoriesChunked;
}


}

但是将所有LinkHashMaps更改为HashMaps并且它可以正常工作。

堆栈跟踪

  

2013年3月20日下午12:37:46 org.apache.catalina.core.StandardWrapperValve调用   严重:servlet [mycompany]的Servlet.service()在路径[/ site]的上下文中引发异常[请求处理失败;嵌套异常是org.thymeleaf.exceptions.TemplateProcessingException:执行处理器'com.mycompany.processor.MenuProcessor'(layout / partials / nav:8)]时出错,但有根本原因   显示java.lang.NullPointerException           在com.mycompany.processor.MenuProcessor.buildMenu(MenuProcessor.java:106)       在com.mycompany.processor.MenuProcessor.modifyModelAttributes(MenuProcessor.java:84)       在org.broadleafcommerce.common.web.dialect.AbstractModelVariableModifierProcessor.processElement(AbstractModelVariableModifierProcessor.java:46)       at org.thymeleaf.processor.element.AbstractElementProcessor.doProcess(AbstractElementProcessor.java:74)       at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)       在org.thymeleaf.dom.Node.applyNextProcessor(Node.java:896)       在org.thymeleaf.dom.Node.processNode(Node.java:858)       在org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:639)       在org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:621)       在org.thymeleaf.dom.Node.processNode(Node.java:876)       在org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:639)       在org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:621)       在org.thymeleaf.dom.Node.processNode(Node.java:876)       在org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:639).....

2 个答案:

答案 0 :(得分:0)

如果这一行真的抛出了nullpointer:

navigationMenu.put(topLvlCat, null);

然后navigationMenu为null。由于linkedHashMap和HashMap都允许空键和值。

我注意到您将navigationMenu定义为public字段,这意味着它可以被任何类更改。这是一种不好的做法,你应该将字段声明为private并提供getter和必要的setter方法。

因此,虽然您正在初始化它,但其他东西可能会将其设置为null。我会检查没有什么可以在另一个类或模板文件中设置navigationMenu。

答案 1 :(得分:0)

这个奇怪的问题变得陌生,它开始工作,即使在删除所有目标文件夹和部署文件夹并重做构建等并且无法正常工作之后,它已经神秘地开始工作第二天。