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判斷重復元素解析及代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
新聞熱點
疑難解答
圖片精選