TreeSet의 기본 층은 Treemap의 Keyset ()이며 Treemap은 빨간색과 검은 나무를 기반으로 구현됩니다. 빨간색과 검은 색 트리는 균형 잡힌 이진 검색 트리로, 모든 노드의 왼쪽과 오른쪽 하위 트리의 높이 차이가 짧은 트리의 두 배를 초과하지 않도록 할 수 있습니다.
Treemap은 키로 정렬되므로 Treeset의 요소도 정렬됩니다. 분명히, 요소가 트리 셋에 삽입 될 때 비교 () 메소드를 호출해야하므로 트리 셋의 요소는 비교 가능한 인터페이스를 구현해야합니다. 트리 셋 세트로서, 중복 요소가 나타나지 않습니다. treeset은 compareto ()를 사용하여 equals ()가 아닌 중복 요소를 판단하고 다음 코드를 참조하십시오.
import java.util.treeset; import org.junit.test; public class testtreeset {class combine embine embinements <private int p1; private int p2; public combine (int p1, int p2) {this.p1 = p1; this.p2 = p2;}@reteper int hashcode () {31 + p2;}@ equals (object.out.print ( "동등한" + this + "및" + obj); 부울 ext = false; if (obj instanceof combine) {system.out.println ( "동일" + this + "및" + obj); 결합 다른 = (combine) obj; rect = (this.p1 == 기타 .getp1 () && this.p2 == 기타. getp2 ());} system.out.println ( ":" + rect); return rect;}@public int compareto (combine o) {system.out.print ( "compare" + this + "및" + o); // p1if (this.p1 <o.p1) {system.out.println (return-1;}) O.p1) {System.out.println ( ", return 1"); return 1;} else} else {system.out.println ( ", return 0"); return 0;}}@public string toString () {return "(" + p1 + "," + p2 + "); {this.p1 = p1;} public int getp2 () {return p2;} public void setp2 (int p2) {this.p2 = p2;}}@test public void test () {cmine c1 = new Combine (1, 2); c2 = new Combine (1, 2); new c4 = compine (1, 3); 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 ());}}}산출:
(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 () 메소드가 호출되지 않음을 알 수 있습니다.
요약
위의 것은 트리셋 판단 반복 요소 분석 및 코드 예제에 관한 것입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!