09_✨TreeSet

charl hi·2022년 6월 21일
0

자바의정석2

목록 보기
9/13

링크텍스트

✨📢✨비교기준

  • ✨1) TreeSet()에 저장되는 객체(treeSet.add(?))가 Comparable을 구현하든가,
  • ✨2) TreeSet(Comparator) 에게 Comparator를 제공해서 정렬기준을 알려줘야 한다.

1. TreeSet()

  • TreeSet은 저절로 정렬하기 때문에 따로 정렬할 필요가 없다!!
    -> 더 정확히 말하자면, 저장되는 요소가 String, Integer ... 일 경우, 기본적으로 Comparable 등의 정렬기준을 구현했기 때문에 내가 따로 정렬기준을 만들 필요가 없는 것?!

1-1) Ex11_13

public class Ex11_13 {

	public static void main(String[] args) {
		Set set = new TreeSet();	//저절로 정렬하기 때문에 따로 정렬할 필요가 없다!!
		
//		for(int i=0; set.size()<6; i++) {
		for(; set.size()<6;) {
			int num = (int)(Math.random()*45)+1;	//1<=x<46
			set.add(new Integer(num));
		}

		System.out.println(set);
	}

}

->

[1, 10, 28, 37, 41, 45]
  • 여기서 TreeSet()에 저장되는 객체인 IntegerComparable을 구현하고 있다!


1-2) Ex11_13_2

package ch11;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class Ex11_13_2 {

	public static void main(String[] args) {
		Set set = new TreeSet();
		
		for(; set.size()<6;) {
			int num = (int)(Math.random()*45)+1;	//1<=x<46
			set.add(new Test());
		}

		System.out.println(set);
	}

}

class Test implements Comparable{
//	비교기준
	@Override
	public int compareTo(Object o) {
		return -1;
	}
}

->

[ch11.Test@3b22cdd0, ch11.Test@1e81f4dc, ch11.Test@4d591d15, ch11.Test@65ae6ba4, ch11.Test@48cf768c, ch11.Test@59f95c5d]
  • 여기서 TreeSet()에 저장되는 객체인 TestComparable을 구현하고 있다!


2. TreeSet(Comparator c)

package ch11;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class Ex11_13_2 {

	public static void main(String[] args) {
		Set set = new TreeSet(new TestComp());	//저절로 정렬하기 때문에 따로 정렬할 필요가 없다!!
		
//		for(int i=0; set.size()<6; i++) {
		for(; set.size()<6;) {
			int num = (int)(Math.random()*45)+1;	//1<=x<46
			set.add(new Test());
		}

		System.out.println(set);
	}

}

class Test {
}

class TestComp implements Comparator{
//	비교기준, TreeSet(Comparator)
	@Override
	public int compare(Object o1, Object o2) {
		return 1;
	}
}

->

[ch11.Test@1e81f4dc, ch11.Test@4d591d15, ch11.Test@65ae6ba4, ch11.Test@48cf768c, ch11.Test@59f95c5d, ch11.Test@5ccd43c2]



범위 검색

subSet()

Ex11_14

링크텍스트



AsciiPrint


public class AsciiPrint {

	public static void main(String[] args) {
		char ch = ' ';
//		공백 ' ' 이후의 문자들을 출력한다.
		for(int i=0; i<95; i++) {
			System.out.print(ch++);
		}

	}

}

->

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~


tailSet(), headSet()

Ex11_15

링크텍스트



트리 순회

  • 이진 트리의 모든노드를 한번씩 읽는 것

순회법

전위 순회법

  • 루트 -> 자식 ... -> 맨밑 왼쪽 자식 -> 오른쪽 자식

중위 순회법

  • 오름차순으로 정렬
  • 왼쪽부터 오른쪽으로~~

후위 순회법

  • 맨밑 왼쪽 자식 -> 오른쪽 자식 -> 부모

층별 순회법

  • 위부터~ 노드 순서대로

0개의 댓글