treeset可以重复吗_java容器(五)HashSet与TreeSet

61e9396ef9493146447d062c29d2eacf.png

了解过HashMap和TreeMap后,学习HashSet和TreeSet就显得很简单了——二者底层分别基于前者来实现。

对于HashSet:

9ac7f527962a2ecddfa57810d0635355.png
HashMap的底层实现通过HashMap完成

25adfdcc0c9e8eec18d7942fe9a958fe.png
本质也是一个HashMap,但是根据Key值来存放,因此是具有不重复性

b5e6d614b2a41efa917da9039eaca681.png
为了简便,所有的value都是一个object对象,PRESENT

至于其余的方法,也基本上是调用了HashMap的方法。

public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
public void clear() {
        map.clear();
    }
public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }
//。。。。。。

值得注意的就是HashSet的无序不可重复性,测试如下:

package myHashMap;
import java.util.HashSet;
import java.util.Set;
public class TestHashSet {
	public static void main(String[] args) {
		Set<String> hashSet=new HashSet<>();
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("a");
		System.out.println(hashSet);
		System.out.println(hashSet.size());
	}

}

6e6e1cdd9de22579bd060237fed3575a.png
HashSet测试结果

对于TreeSet:

对比HaseSet——>TreeSet底层是有TreeMap实现,具有有序不可重复性的特点。

注:所谓无序和有序我的理解是——输出是否可以与插入元素顺序无关,无关则是有序,有关则是无序,就比如HashSet输出时的顺序总是和插入顺序一致,而TreeSet就可以按照key值排序。

测试如下:

package myHashMap;
import java.util.Set;
import java.util.TreeSet;
public class TestTreeSet {
	public static void main(String[] args) {
		Set<Integer> treeset = new TreeSet<>();
		treeset.add(300);
		treeset.add(100);
		treeset.add(400);
		System.out.println(treeset);
		
		Set<Emp1> treeset1=new TreeSet<>();
		treeset1.add(new Emp1(10, "张三", 2000));
		treeset1.add(new Emp1(2, "王五", 1000));
		treeset1.add(new Emp1(1, "李二", 2000));
        System.out.println(treeset1);
	}

}

class Emp1 implements Comparable<Emp1> {
	public Emp1(int id, String name, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	int id;
	String name;
	double salary;

	@Override
	public String toString() {
		return "id=" + this.id + " name=" + this.name + " salary=" + this.salary;
	}
	@Override
	public int compareTo(Emp1 o) {
		if (this.salary > o.salary) {
			return 1;
		} else if (this.salary < o.salary) {
			return -1;
		} else {
			if (this.id > o.id) {
				return 1;
			} else if (this.id < o.id) {
				return -1;
			} else {
				return 0;
			}
		}
	}

}

818e0deb9af229f07fe22dcd7fbc879d.png
TreeSet也可以和TreeMap一样按照key值递增排序
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值