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;
        }
  • 相关阅读:
    状态同步和帧同步
    SVN和Git的使用
    客户端知识点
    客户端性能优化
    H5游戏开发面试经验
    2.0 pomelo-treasure官方demo的使用
    1.0 pomelo环境的搭建和部署
    python 网络编程
    冒泡排序
    面向对象-反射和元类
  • 原文地址:https://www.cnblogs.com/noaman/p/8764287.html
Copyright © 2011-2022 走看看