SortedMap
优质
小牛编辑
139浏览
2023-12-01
SortedMap接口扩展了Map。 它确保条目按升序键维护。
当调用映射中没有任何项时,有几种方法会抛出NoSuchElementException。 当对象与地图中的元素不兼容时,抛出ClassCastException。 如果在映射中不允许null时尝试使用null对象,则抛出NullPointerException。
SortedMap声明的方法总结在下表中 -
Sr.No. | 方法和描述 |
---|---|
1 | Comparator comparator( ) 返回调用有序映射的比较器。 如果自然排序用于调用映射,则返回null。 |
2 | Object firstKey( ) 返回调用映射中的第一个键。 |
3 | SortedMap headMap(Object end) 返回键小于结束的那些映射条目的有序映射。 |
4 | Object lastKey( ) 返回调用映射中的最后一个键。 |
5 | SortedMap subMap(Object start, Object end) 返回包含键大于或等于start且小于end的条目的映射。 |
6 | SortedMap tailMap(Object start) 返回包含键大于或等于start的条目的映射。 |
例子 (Example)
SortedMap在TreeMap等各种类中实现。 以下是解释SortedMap functionlaity的示例 -
import java.util.*;
public class TreeMapDemo {
public static void main(String args[]) {
// Create a hash map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("Zara", new Double(3434.34));
tm.put("Mahnaz", new Double(123.22));
tm.put("Ayan", new Double(1378.00));
tm.put("Daisy", new Double(99.22));
tm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)tm.get("Zara")).doubleValue();
tm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + tm.get("Zara"));
}
}
这将产生以下结果 -
输出 (Output)
Ayan: 1378.0
Daisy: 99.22
Mahnaz: 123.22
Qadir: -19.08
Zara: 3434.34
Zara's new balance: 4434.34