TreeSet的底層是TreeMap的keySet(),而TreeMap是基于紅黑樹(shù)實(shí)現(xiàn)的,紅黑樹(shù)是一種平衡二叉查找樹(shù),它能保證任何一個(gè)節(jié)點(diǎn)的左右子樹(shù)的高度差不會(huì)超過(guò)較矮的那棵的一倍。
成都創(chuàng)新互聯(lián)成立于2013年,我們提供高端網(wǎng)站建設(shè)公司、網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、網(wǎng)站定制、全網(wǎng)整合營(yíng)銷推廣、微信小程序開(kāi)發(fā)、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站推廣服務(wù),提供專業(yè)營(yíng)銷思路、內(nèi)容策劃、視覺(jué)設(shè)計(jì)、程序開(kāi)發(fā)來(lái)完成項(xiàng)目落地,為雨棚定制企業(yè)提供源源不斷的流量和訂單咨詢。TreeMap是按key排序的,所以TreeSet中的元素也是排好序的。顯然元素在插入TreeSet時(shí)compareTo()方法要被調(diào)用,所以TreeSet中的元素要實(shí)現(xiàn)Comparable接口。TreeSet作為一種Set,它不允許出現(xiàn)重復(fù)元素。TreeSet是用compareTo()來(lái)判斷重復(fù)元素的,而非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); // 排序時(shí)只考慮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 (); 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()); } } }