`

TreeMap用法 示例

    博客分类:
  • Java
 
阅读更多

/*

TreeMap类通过使用树来实现Map接口.TreeMap提供了按排序顺序存储关键字/值对的有效手段,同时允许快速检索。不像散列映射,树映射保证它的元素按照关键字升序排序。

*/

import java.util.*;
class TreeMapDemo{
 public static void main(String[] args)
 {
  //Creat a tree map
  TreeMap tm = new TreeMap();

  //Put elements to the map
  tm.put("Evan",new Double(12345.77));
  tm.put("Rose",new Double(78777));
  tm.put("Magic",new Double(-99.10));
  tm.put("Mike",new Double(100.00));
  tm.put("Sue",new Double(17.15));

  //Get a set of 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.println(me.getKey() + ": ");
   System.out.println(me.getValue());
  }
  System.out.println();

  //Deposit 1000 into Evan's account
  double balance = ((Double)tm.get("Evan")).doubleValue();
  tm.put("Evan",new Double(balance + 1000));
  System.out.println("Evan's new balance : " + tm.get("Evan"));
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics