# java treeset 重复_TreeSet判断重复元素解析及代码示例

TreeSet的底层是TreeMap的keySet()，而TreeMap是基于红黑树实现的，红黑树是一种平衡二叉查找树，它能保证任何一个节点的左右子树的高度差不会超过较矮的那棵的一倍。

TreeMap是按key排序的，所以TreeSet中的元素也是排好序的。显然元素在插入TreeSet时compareTo()方法要被调用，所以TreeSet中的元素要实现Comparable接口。TreeSet作为一种Set，它不允许出现重复元素。TreeSet是用compareTo()来判断重复元素的，而非equals()，看下面代码。

import java.util.TreeSet;

import org.junit.Test;

public class TestTreeSet {

class Combine implements Comparable {

private int p1;

private int p2;

public Combine(int p1, int p2) {

this.p1 = p1;

this.p2 = p2;

}

@Override

public int hashCode() {

return p1 * 31 + p2;

}

@Override

public Boolean equals(Object obj) {

System.out.print("whether equal " + this + " and " + obj);

Boolean rect = false;

if (obj instanceof Combine) {

System.out.println("whether equal " + this + " and " + obj);

Combine other = (Combine) obj;

rect = (this.p1 == other.getP1() && this.p2 == other.getP2());

}

System.out.println(": " + rect);

return rect;

}

@Override

public int compareTo(Combine o) {

System.out.print("compare " + this + " and " + o);

// 排序时只考虑p1

if (this.p1 < o.p1) {

System.out.println(", return -1");

return -1;

} else if (this.p1 > o.p1) {

System.out.println(", return 1");

return 1;

} else {

System.out.println(", return 0");

return 0;

}

}

@Override

public String toString() {

return "(" + p1 + "," + p2 + ")";

}

public int getP1() {

return p1;

}

public void setP1(int p1) {

this.p1 = p1;

}

public int getP2() {

return p2;

}

public void setP2(int p2) {

this.p2 = p2;

}

}

@Test

public void test() {

Combine c1 = new Combine(1, 2);

Combine c2 = new Combine(1, 2);

Combine c3 = new Combine(1, 3);

Combine c4 = new Combine(5, 2);

TreeSet set = new TreeSet();

while (!set.isEmpty()) {

//按顺序输出TreeSet中的元素

Combine combine = set.pollFirst();

System.out.println(combine.getP1() + "\t" + combine.getP2());

}

}

}

compare (1,2) and (1,2), return 0

compare (1,2) and (1,2), return 0

compare (1,3) and (1,2), return 0

compare (5,2) and (1,2), return 1

1 2

5 2

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
11-29
10-10 1088
07-04 794
07-30 968
01-18 1504
12-09 809
02-13 2903
05-18 2550
10-30 1733

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

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

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