> Java > java지도 시간 > 본문

자바의 트리셋

王林
풀어 주다: 2024-08-30 15:07:03
원래의
526명이 탐색했습니다.

Java의 TreeSet은 저장에 도움이 되는 SortedSet 인터페이스의 주요 구현 중 하나로 간주됩니다. 여기서 요소는 자연 순서 또는 명시적 비교자를 기반으로 하는 순서로 설정되는 방식으로 정렬됩니다. TreeSet은 AbstractSet 클래스를 상속하고 NavigableSet 인터페이스를 구현합니다. HashSet과 유사하지만 순서를 유지하지만 HashSet은 순서를 유지하지 않습니다. 또한 HashSet과 달리 TreeSet에서는 null 요소를 허용합니다. TreeSet에 대한 자세한 내용은 다음 섹션에서 설명합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

트리셋의 특징

TreeSet의 주요 기능은 다음과 같습니다.

  • 중복된 ​​값은 허용되지 않습니다.
  • 오름차순으로 개체가 정렬됩니다.
  • 게재 순서는 유지되지 않습니다. 그 외에도 요소는 키를 기준으로 정렬됩니다.
  • 이종 개체는 삽입할 수 없습니다. 삽입하려고 하면 런타임 중에 classCastException이 발생합니다.
  • 엄청난 양의 정렬된 데이터를 저장하세요.
  • 검색 시간이 빠릅니다.
  • 빠른 접속.
  • Null 요소는 허용되지 않습니다.
  • 추가, 검색, 제거와 같은 작업에는 O(log n)의 시간이 걸립니다.
  • n개의 요소를 인쇄하는 등의 작업의 경우 O(n)의 시간 복잡도가 존재합니다.
  • 동기화되지 않았습니다.
  • TreeMap의 존재는 요소를 저장하기 위해 존재합니다.
  • 스레드로부터 안전하지 않습니다.

구문:

TreeSet을 생성하려면 먼저 java.util.TreeSet 패키지를 가져옵니다. 그런 다음 다음 구문을 사용하여 TreeSet을 생성합니다.

TreeSet<Integer> num= new TreeSet<>();
로그인 후 복사

인수를 언급하지 않고 TreeSet을 만들었으므로 요소는 자연스러운 순서로 정렬됩니다. 즉, 오름차순입니다.

이미 언급했듯이 정렬은 인터페이스 비교기를 사용하여 사용자 정의할 수 있습니다.

Java의 TreeSet 생성자

Java의 TreeSet에는 4개의 생성자가 있습니다. 그들은:

  1. TreeSet(): 자연 순서에 따른 정렬을 통해 비어 있는 새 TreeSet이 생성됩니다.
  2. TreeSet(Collectionc): 컬렉션 c에서 언급된 요소로 새 TreeSet이 생성되며 자연 순서에 따라 정렬됩니다.
  3. TreeSet(Comparator comparator): 언급된 비교자를 기준으로 정렬하여 비어 있는 새 TreeSet이 생성됩니다.
  4. TreeSet(SortedSet s): sortedset s에 언급된 요소와 동일한 순서로 새로운 TreeSet이 생성됩니다.

Java의 TreeSet 메서드

TreeSet에는 여러 가지 기능을 수행해야 합니다. 그것이 무엇인지 살펴보겠습니다.

  • add(Ee): An element e will be added to the set if it is not present in it.
  • addAll(CollectionE> c): All the elements in collection c will be added to the set.
  • E ceiling(Ee): The last element which is greater than or equal to the element in the set will be returned.
  • clear(): All the elements in the set will be removed.
  • clone(): A shallow copy will be returned for the TreeSet instance.
  • comparator(): The comparator used in the set will be returned. If natural ordering is used, null will be returned.
  • contains(Objecto): If the set contains the element o, true will be returned.
  • descendingIterator(): An iterator will be returned over the elements in descending order.
  • descendingSet(): A reverse order view will be returned for the elements present in the list.
  • first(): he first or the lowest element in the set will be returned.
  • last(): The last or the largest element in the set will be returned.
  • iterator(): n iterator will be returned over the elements in ascending order.
  • lower(Ee): The greatest element will be returned which is strictly small than the element e which is given. If there is no such element, null will be returned.
  • higher(Ee): The smallest element will be returned which is strictly high than the element e which is given. If there is no such element, null will be returned.
  • isEmpty(): True will be returned if no elements are present.
  • size(): The number of elements in the set will be returned. In other words, cardinality will be returned.
  • pollFirst(): The first or the lowest element in the set will be retrieved and removed. If there are no elements in the set, the null will be returned.
  • pollLast(): The last or the highest element in the set will be retrieved and removed. If there are no elements in the set, the null will be returned.
  • remove(Objecto): If the set contains the element o, it will be removed.
  • subSet(EfromElement, boolean fromInclusive, E toElement, boolean toInclusive): A view will be returned for the portion of the set from the range from Element to toElement.
  • subSet(EfromElement, E toElement): A view will be returned for the portion of the set from the range fromElement(inclusive) to toElement(exclusive).
  • tailSet(EfromElement):  view will be returned for the portion of the set where elements are larger than fromElement.
  • tailSet(EfromElement, boolean inclusive): A view will be returned for the portion of the set where elements are larger than fromElement. It is considered if inclusive is true.

Example of TreeSet in Java

Java program to create a tree set with the natural ordering of elements.

import java.util.SortedSet;
import java.util.TreeSet;
//class
public class TreeSetExample {
//main method
public static void main(String[] args) {
//  TreeSet <u>fam</u> creation
SortedSet<String> fam = new TreeSet<>();
// Adding new elements to a TreeSet
fam.add("Anna");
fam.add("Adam");
fam.add("Sam");
fam.add("Iza");
//print the treeset
System.out.println("Fam Set : " + fam);
// Trying to add duplicate element <u>Anna</u>
fam.add("Anna");
System.out.println("Added element Anna, Now the treeset is : " + fam);
// Trying to add  element <u>Anna</u> with lower case
fam.add("anna");
System.out.println("Added element anna, Now the treeset is  : " + fam);
}
}
로그인 후 복사

Output:

자바의 트리셋

A treeset fam is created first. Once it is created, elements are added to it and the whole treeset is printed. After this, an element ‘Anna’ which is already present in the treeset is trying to get added. Since duplicates are not allowed in TreeSet, it is not get added. After that, an element ‘anna’ which is the lower case of the already existing element ‘Anna’ is added. Since it is in lowercase, it gets added to the treeset without any problem.

Conclusion

TreeSet in Java is an implementation of the interface SortedSet that helps in storage where the elements are arranged in natural ordering or based on the comparator. Several aspects of TreeSet is discussed in this document.

위 내용은 자바의 트리셋의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!