Java SortedMap 接口
2018-11-24 18:20 更新
Java SortedMap 接口
SortedMap接口扩展Map。它确保项目保持在升序键顺序。
有几种方法没有项目在调用映射时抛出一个NoSuchElementException异常。当一个对象在Map上的元素不兼容抛出一个ClassCastException异常。如果试图使用一个空对象时或在map上不允许空值时一个NullPointerException异常被抛出。
通过SortedMap的声明的方法总结如下表:
| 序号 | 方法描述 |
|---|---|
| 1 | Comparator comparator( ) 返回调用的有序映射的比较器。如果自然顺序用于调用映射,则返回null。 |
| 2 | Object firstKey( ) 返回调用映射的第一个键。 |
| 3 | SortedMap headMap(Object end) 返回的有序映射为那些映射条目与小于结束键。 |
| 4 | Object lastKey( ) 返回调用映射的最后一个键。 |
| 5 | SortedMap headMap(Object end) 返回的有序映射为那些映射条目与小于结束键。 |
| 6 | SortedMap tailMap(Object start) 返回包含与是大于或等于开始键的那些条目的映射。 |
实例
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"));
}
}
以上实例编译运行结果如下:
Ayan: 1378.0 Daisy 99.22 Mahnaz: 123.22 Qadir: -19.08 Zara: 3434.34 Zara.s current balance: 4434.34
以上内容是否对您有帮助:

免费 AI IDE


更多建议: