TreeSet

dawn·2021년 3월 12일
0

자바

목록 보기
1/9

TreeSet에 객체를 저장하면 자동으로 정렬되는데 부모값과 비교해서 낮은 것은 왼쪽 자식 노드에, 높은 것은 오른쪽 자식 노드에 저장한다.

1. TresesSet생성

TreeSet<E> treeSet = new TreeSet<E>();

Set인터페이스 타입 변수에 대입해도 되지만 TreeSet클래스 타입으로 대입한 이유는 객체를 찾거나 범위 검색과 관련된 메소드를 사용하기 위해서이다. 다음 예제는 점수를 무작위로 저장하고 특정 점수를 찾는 방법을 보여준다.

public class TreeSetExample {
	public static void main(String[] args) {
		TreeSet<Integer> scores = new TreeSet<>();
		scores.add(10);
		scores.add(50);
		scores.add(20);
		scores.add(30);
		scores.add(70);
		scores.add(80);
		scores.add(60);
		
		Integer score = null;
		
		System.out.println("TreeSet 사이즈 : "+scores.size());
		
		score = scores.first(); //제일 낮은 객체를 리턴 10
		System.out.println("가장 낮은 점수:" + score);
		
		score = scores.last(); //제일 높은 객체를 리턴 80
		System.out.println("scores.last() : " + score);
		
		score = scores.lower(50); //주어진 객체보다 바로 아래 객체를 리턴 30
		System.out.println("scores.lower() : " + score);
		
		score = scores.higher(40); //주어진 객체보다 바로 위 객체를 리턴 //매개변수로 존재하지 않는것 줘도 됩니다.
		System.out.println("scores.higher() : " + score);
		
		scores.floor(80); //주어진 객체와 동등한 객체가 있으면 리턴, 만약 없다면 주어진 객체의 바로 아래의 객체를 리턴
		
		score = scores.pollFirst(); //제일 낮은 객체를 꺼내오고 컬렉션에서 제거함
		System.out.println("scores.pollFirst() : " + score);
		System.out.println("TreeSet 사이즈 : "+scores.size());
	}
}

2. 범위검색

TreeSet은 범위검색 관련된 메소드들을 제공한다.
그 중 하나인 subSet() 메소드를 이용해 영어단어를 정렬하고, 범위를 검색하는 예제를 작성하였다.

public class TreeSetNavigableSet {
	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<>();
		treeSet.add("zoo");
		treeSet.add("darry");
		treeSet.add("hoter");
		treeSet.add("Vaseline");
		treeSet.add("thumbnail");
		treeSet.add("cherry");
		
		System.out.println("[c~h 사이의 단어 검색]");
		NavigableSet<String> rangeSet = treeSet.subSet("c", true, "h", true);
		for(String word : rangeSet) {
			System.out.println(word); //hoter가 출력이 안되네요,,,?
		}
	}
}

3. 정렬

TreeSet은 정렬과 관련된 메소드들은 제공한다.

  • descendingIterator() : 내림차순으로 정렬된 Iterator 객체를 리턴
  • descendingSet() : 내림차순으로 정렬된 NavigableSet을 반환
    오름차순으로 정렬하고 싶다면 descendingSet()을 두번 호출하면 된다.
'이것이 자바다'라는 책을 참고해 작성한 내용입니다.
profile
안녕하세요

1개의 댓글

comment-user-thumbnail
2021년 4월 5일

지나가다가 글을 남겨요.

사전의 목차를 생각하시면,
범위 시작~'h' 한 글자까지 보시면, 'h' 한 글자 뒤의 범위는 제외가 되어요.

'c'를 포함해서 'c' 첫글자를 포함한 단어~'h' 한 글자까지 범위가 포함되지만,
'h' 한 글자 이후의 'h' + 'a' 처럼, 'h'로 시작하는 단어들 예) "ha"나 "hzzzz"는 포함이 안되어요~

예제 소스에서 treeSet.add("h");를 추가하신 뒤,
실행하시면, 결과에 'h'까지는 포함이 되지만,
'h'이후의 'h' + 어떤 글자가 포함된 "hoter"는 출력되지 않아요.

만약에 "hoter" 출력을 원하시면, 'h'로 시작하고 'z'로 끝날 수 있도록,
예제 소스에서 treeSet.subSet("c", true, "hp", true);나 treeSet.subSet("c", true, "hzzzz", true);로 수정해보시겠어요?

답글 달기