ツリーセットの基礎となる層はTreemapのKeyset()であり、Treemapは赤と黒の木に基づいて実装されています。赤と黒の木はバランスの取れたバイナリ検索ツリーであり、任意のノードの左サブツリーと右のサブツリーの高さの差が、短い木の2倍を超えないようにすることができます。
Treemapはキーによってソートされるため、Treesetの要素もソートされます。明らかに、要素がツリーセットに挿入されたときに比較()メソッドを呼び出す必要があるため、ツリーセットの要素は同等のインターフェイスを実装する必要があります。セットとしてツリーセットでは、複製要素が表示されません。 TreesetはCompareTo()を使用して、等しい()ではなく重複要素を判断します。次のコードを参照してください。
Import java.util.treeset; Import org.junit.test; public class testtreeSet {class combine combine combine <combine> {private int p1; private int p2; public combine(int p1、int p2){this.p1 = p1; this.p2 = p2;} boolean equals(object obj){system.out.print( "equal" + this + "and" + obj); boolean rect = false; if(obj instanceof combine){system.out.println( "equal" + "and" + obj); combine other =(combine)obj; other.getp2());} system.out.println( ":" + rect); return rect;}@override public int compareto(combine o){system.out.print( "compare" + this + "and"; (this.p1> o.p1){system.out.println( "、return 1"); return 1;} els {system.out.println( "、return 0"); return 0;}}@override public string toString(){){return "(" + p1 + "、" + p2 + " p1){this.p1 = p1;} public int getp2(){return p2;} public void setp2(int p2){this.p2 = p2;}}@public void test(){combine c1 = new combine(1、2); combine c2 = new combine(1、2); combine combine(1、2); 2); treeset <combine> set = new treeset <combine>(); set.add(c1); set.add(c2); set.add(c3); set.add(c4); while(!set.isempty()){// combine = set.pollfirst(); system.out.println(combine.getp1() + "/t" + combine.getp2();}}}}}} combine = set.out.println(combine.out.println(combine.out.println)の順に並べて出力します。出力:
(1,2)と(1,2)を比較して、0を返します
(1,2)と(1,2)を比較して、0を返します
(1,3)と(1,2)を比較して、0を返します
(5,2)と(1,2)を比較して、1を返します
1 2
5 2
compareto()が等しいかどうかに関係なく、equals()メソッドは呼び出されないことがわかります。
要約します
上記は、Treeset Judwersの反復要素分析とコードの例に関するすべてです。私はそれが誰にでも役立つことを願っています。興味のある友人は、このサイトの他の関連トピックを引き続き参照できます。欠点がある場合は、それを指摘するためにメッセージを残してください。このサイトへのご支援をありがとうございました!