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岁
原文地址:https://www.cnblogs.com/jkgyu/p/15517383.html