TreeSet的底層是TreeMap的keySet(),而TreeMap是基于紅黑樹實(shí)現(xiàn)的,紅黑樹是一種平衡二叉查找樹,它能保證任何一個(gè)節(jié)點(diǎn)的左右子樹的高度差不會超過較矮的那棵的一倍。
TreeMap是按key排序的,所以TreeSet中的元素也是排好序的。顯然元素在插入TreeSet時(shí)compareTo()方法要被調(diào)用,所以TreeSet中的元素要實(shí)現(xiàn)Comparable接口。TreeSet作為一種Set,它不允許出現(xiàn)重復(fù)元素。TreeSet是用compareTo()來判斷重復(fù)元素的,而非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); // 排序時(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<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()); } } }
標(biāo)題名稱:TreeSet判斷重復(fù)元素解析及代碼示例-創(chuàng)新互聯(lián)
標(biāo)題網(wǎng)址:http://www.sd-ha.com/article22/dgjjjc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、網(wǎng)站內(nèi)鏈、做網(wǎng)站、網(wǎng)站維護(hù)、手機(jī)網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容