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岁
  • 相关阅读:
    ZOJ Problem Set–2417 Lowest Bit
    ZOJ Problem Set–1402 Magnificent Meatballs
    ZOJ Problem Set–1292 Integer Inquiry
    ZOJ Problem Set–1109 Language of FatMouse
    ZOJ Problem Set–1295 Reverse Text
    ZOJ Problem Set–1712 Skew Binary
    ZOJ Problem Set–1151 Word Reversal
    ZOJ Problem Set–1494 Climbing Worm
    ZOJ Problem Set–1251 Box of Bricks
    ZOJ Problem Set–1205 Martian Addition
  • 原文地址:https://www.cnblogs.com/jkgyu/p/15517383.html
Copyright © 2011-2022 走看看