当前位置: 移动技术网 > IT编程>开发语言>Java > TreeSet判断重复元素解析及代码示例

TreeSet判断重复元素解析及代码示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

曾道人利彩利民高手坛,泰兴论坛,wwe2014年5月20日

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<combine> {
		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<combine> set = new treeset<combine>();
		set.add(c1);
		set.add(c2);
		set.add(c3);
		set.add(c4);
		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

我们看到不论compareto()返回的是不是相等,equals()方法都没有被调用。

总结

以上就是本文关于treeset判断重复元素解析及代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网