>  기사  >  Java  >  Java의 TreeMap이란 무엇입니까?

Java의 TreeMap이란 무엇입니까?

王林
王林원래의
2024-08-30 15:45:46650검색

TreeMap은 추상 클래스와 함께 사용되어 Java에서 Map 및 NavigableMap 인터페이스를 배포합니다. 맵은 키의 자연스러운 순서에 따라 또는 빌더에 따라 미리 작성된 비교기에 따라 정렬됩니다. 이는 키-값 쌍을 정렬하고 저장하는 쉬운 방법입니다. 트리맵에 유지되는 저장 순서는 특정 비교자에 관계없이 다른 분류된 맵과 동일해야 합니다.

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

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

TreeMap의 속성은 다음과 같습니다.

  • 독특한 요소들로 구성되어 있습니다.
  • 널 키를 가질 수 없습니다.
  • null 값을 여러 번 가질 수 있습니다.
  • 동기화되지 않았습니다.

선언:

public class TreeMap<Key, Value> extends AbstractMap<Key, Value>implements NavigableMap<Key, Value>, Cloneable, Serializable

여기서 Key와 Value는 각각 이 맵의 키 유형과 매핑된 값입니다.

TreeMap 생성자

TreeMap의 생성자는 다음과 같습니다.

  • TreeMap(): 새 빈 트리맵은 키 순서를 자연스럽게 구성하여 구성됩니다.
  • TreeMap( 비교기 Key> 비교기): 비교기에 지정된 키 순서에 따라 비어 있는 새 트리맵이 구성됩니다.
  • TreeMap( MapK어,? Ext V값> m): 맵 m의 매핑을 사용하여 새 트리맵이 구성되고 자연스럽게 키 순서가 지정됩니다.
  • TreeMap( SortedMap<K어,? 확장V값> m): 맵 m의 매핑과 비교기에 지정된 키 순서를 사용하여 새 트리맵이 구성됩니다.

TreeMap의 방법

TreeMap은 다양한 기능을 수행하는 데 도움이 되는 다양한 메서드 컬렉션을 제공합니다. 그들은:

  • clear(): All the mapping in the map will be removed.
  • clone(): A shallow copy will be returned for the TreeMap instance.
  • containsKey(Objectk): If there is mapping available for the specified key, true will be returned.
  • containsValue(Objectv): If there is mapping available for one or more keys for the value v, true will be returned.
  • ceilingKey(Kkey): Least key which is larger than or equal to the specified key will be returned. If there is no key, then null will be returned.
  • ceilingEntry(Kkey): Key-value pair for the least key, which is larger than or equal to the specified key will be returned. If there is no key, then null will be returned.
  • firstKey(): First or last key in the map will be returned.
  • firstEntry(): Key-value pair for the least or first key in the map will be returned. If there is no key, then null will be returned.
  • floorKey(Kkey): The Largest key, which is less than or equal to the specified key, will be returned. If there is no key, then null will be returned.
  • floorEntry(Kkey): Key-value pair for the largest key, which is less than or equal to the specified key, will be returned. If there is no key, then null will be returned.
  • lastKey(): Highest or last key in the map will be returned.
  • lastEntry(): Key-value pair for the largest key in the map will be returned. If there is no key, then null will be returned.
  • lowerKey(Kkey): The Largest key, which is strictly smaller than the specified key, will be returned. If there is no key, then null will be returned.
  • lowerEntry(Kkey): Key-value pair for the largest key, which is strictly smaller than the specified key, will be returned. If there is no key, then null will be returned.
  • remove(Objectk): Mapping for the specified key in the map will be removed.
  • size(): Count of key-value pairs in the map will be returned.
  • higherEntry(Kkey): Key-value pair for the smallest key, which is strictly larger than the specified key, will be returned. If there is no key, then null will be returned.
  • higherKey(Kkey): The Smallest key, which is strictly higher than the specified key, will be returned. If there is no key, then null will be returned.
  • descendingMap(): Reverse order will be returned for the mappings.
  • entrySet(): Set view will be returned for the mappings.
  • get(Objectk): The value of the specified key will be returned. If the key does not contain any mapping, then null will be returned.
  • keySet(): Set view will be returned for the keys.
  • navigableKeySet(): NavigableSet view will be returned for the keys.
  • pollFirstEntry(): Key-value pair for the least or first key in the map will be removed and returned. If the map is empty, then null will be returned.
  • pollLastEntry(): Key-value pairs for the greatest key in the map will be removed and returned. If the map is empty, then null will be returned.
  • values(): Collection view will be returned for the values in the map.

Example to Implement TreeMap in Java

Now, let us see a sample program to create a treemap and add elements to it.

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String args[]) {
// Tree Map creation
TreeMap tmap = new TreeMap();
// Add elements to the treemap tmap
tmap.put("Anna Jeshua", new Double(3459.70));
tmap.put("Annamu Jeshua", new Double(321.56));
tmap.put("Izanorah Denan", new Double(1234.87));
tmap.put("Adam Jeshua", new Double(89.35));
tmap.put("Anabeth Jeshua", new Double(-20.98));
// Retrieve the entry set of treemap
Set set = tmap.entrySet();
// Create an iterator itr
Iterator itr = set.iterator();
// Display the elements in treemap using while loop
while(itr.hasNext()) {
Map.Entry mp = (Map.Entry)itr.next();
System.out.print(" Key : " + mp.getKey() + ";");
System.out.println(" Value : "+ mp.getValue());
}
System.out.println();
// Add 2500 to Anabeth's value
double val = ((Double)tmap.get("Anabeth Jeshua")).doubleValue();
tmap.put("Anabeth Jeshua", new Double(val + 2500));
System.out.println("Anabeth's new value: " + tmap.get("Anabeth Jeshua"));
} }

Output:

Keys and corresponding values of the TreeMap will be displayed on executing the code.

Java의 TreeMap이란 무엇입니까?

Explanation:

  • 먼저 TreeMap을 생성하고 요소를 추가합니다.
  • 요소를 표시하려면 반복자를 만들어야 합니다.
  • 반복자를 사용하면 모든 키와 해당 값이 표시됩니다.
  • 키 값에 2500을 더하려면 put() 메소드도 사용됩니다.

결론

Java TreeMap은 키-값 쌍을 정렬된 순서로 저장하는 데 도움이 되는 Red-Black 트리를 구현한 것입니다. 이 문서에서는 Java TreeMap의 선언, 생성자, 메소드 및 샘플 프로그램과 같은 여러 세부 사항을 자세히 설명합니다.

위 내용은 Java의 TreeMap이란 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 별칭다음 기사:자바 별칭