zoukankan      html  css  js  c++  java
  • HashSet和TreeSet的异同

    最近用Set解决自定义实体重复数据的问题,突然发现Set的Add方法返回了false。猜测应该是相同元素add时,后续添加的会直接舍弃而不像Map一下被覆盖。顺便测试了下两者的差异

    HashSet的Add方法,触发的是equals和hashCode方法,因为其容器是个HashMap对象。另,equals中的属性,要在hashCode中体现

    TreeSet的Add方法,触发的是compareTo方法,因为其实现了SortedSet接口用户排序

    代码如下

    package test;
    
    import lombok.Data;
    import org.ahocorasick.trie.Emit;
    import org.ahocorasick.trie.Trie;
    import org.junit.Test;
    
    import java.util.*;
    
    import static org.junit.Assert.fail;
    
    public class UtilTest {
    
        @Test
        public void testInitRoleAuthTable() {
            testEntity a = new testEntity();
            testEntity b = new testEntity();
            a.setName("a");
            a.setAge("20岁");
            b.setName("a");
            b.setAge("30岁");
            Set<testEntity> testEntitySet = new TreeSet<>();
            testEntitySet.add(a);
            testEntitySet.add(b);
            for(testEntity item:testEntitySet){
                System.out.println(item.toString());
            }
    
            Set<testEntity> testEntityhashSet = new HashSet<>();
            testEntityhashSet.add(a);
            testEntityhashSet.add(b);
            for(testEntity item:testEntityhashSet){
                System.out.println(item.toString());
            }
        }
    
    }
    @Data
    class testEntity implements Comparable<testEntity>{
        private String name;
        private String age;
        @Override
        public int compareTo(testEntity o){
            return this.name.compareTo(o.getName());
        }
        @Override
        public boolean equals(Object entity){
            testEntity entity2 = (testEntity)entity;
            if(this.name.equals(entity2.name)){
                return true;
            }
            return false;
        }
        @Override
        public String toString(){
            return  "name:"+this.name+" ;age:"+this.age;
        }
        @Override
        public int hashCode() {
            return this.name.hashCode();
        }
    }

     执行结果如下

    name:a ;age:20岁
    name:a ;age:20岁
  • 相关阅读:
    009-LSTM网络-长短记忆网络
    008---递归神经网络-RNN
    007-卷积神经网络03-前向传播-反向传播
    006-卷积神经网络02-池化层,全连接层
    005-卷积神经网络01-卷积层
    004-神经网络
    003-神经网络基础-最优化,前向传播,反向传播
    002-神经网络基础-得分函数,SVM损失函数,正则化惩罚项,softmax函数,交叉熵损失函数
    001-神经网络基础-K近邻算法
    DBSCAN聚类算法
  • 原文地址:https://www.cnblogs.com/jkgyu/p/15517383.html
Copyright © 2011-2022 走看看