zoukankan      html  css  js  c++  java
  • 【SSM电商项目后台开发】递归查找品类--&--去重的时候重写Hashcode

    一、查找某个节点下的所有节点(下一层平级)

    >传入parentId,查找下面一层的所有parentId为指定值的节点。

        @Override
        public ServerResponse getChildrenParallelCategory(Integer categoryId){
            if (categoryId == null){
                return ServerResponse.createByErrorMsg("参数错误");
            }
            List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
            if (CollectionUtils.isEmpty(categoryList)){
                logger.info("未找到当前分类的子类");
            }
            return ServerResponse.createBySuccess(categoryList);
        }

    二、递归查找某个节点下的所有节点

    //递归算法,算出子节点
        //注意:此处 用Set去重Category,需要对Category重写Hashcode和equals方法
        public Set<Category> findChildCategory(Set<Category> categorySet, Integer categoryId){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category != null){
                categorySet.add(category);
            }
    
            //递归查找子节点
            List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
            for (Category categoryItem:categoryList) {
                findChildCategory(categorySet, categoryItem.getId());
            }
            return categorySet;
        }

    三、使用Set去重的时候,需要考虑到HashCode问题,对里面类型进行重写HashCode和equals方法

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Category category = (Category) o;
    
            return !(id != null ? !id.equals(category.id) : category.id != null);
    
        }
    
        @Override
        public int hashCode() {
            return id != null ? id.hashCode() : 0;
        }
  • 相关阅读:
    COJ 1002 WZJ的数据结构(二)(splay模板)
    生成网络流图
    最小费用最大流MCMF zkw费用流
    COJ 2003 选根 (树的重心)
    最小费用最大流MCMF 最小增广
    PDO 基础知识
    使 用 Jquery 全选+下拉+单选+事件+挂事件
    搜 房 网 站 设 计 练 习
    百分比进度条
    在PHP系统里连接MySQL 数据访问,+ + + + + 数据删除
  • 原文地址:https://www.cnblogs.com/noaman/p/8764287.html
Copyright © 2011-2022 走看看