论坛首页 Java企业应用论坛

Hashtable 示例

浏览 2068 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-11-07   最后修改:2008-11-07

//Demonstrate a Hashtable.
import java.util.*;
class HTDemo{
 public static void main(String[] args)
 {
  Hashtable balance = new Hashtable();
  Enumeration names;
  String strName;
  double dblBal;

  balance.put("Sue Yuan",new Double(17.15));
  balance.put("Jiahui Sheng",new Double(78777));
  balance.put("Huajiang Chen",new Double(12345.77));
  balance.put("Magic Ya",new Double(-99.10));
  balance.put("Quanbing Chen",new Double(100.00));
 
  //Show all balances in hashtable.
  names = balance.keys();
  while(names.hasMoreElements()){
   strName = (String)names.nextElement();
   System.out.println(strName  + ": " + balance.get(strName));
  }
  System.out.println();

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

/*

和映射类一样,Hashtable不直接支持迭代函数。因此上面的程序使用枚举来显示balance内容。我们可以获得允许使用迭代函数的散列表的集合视图。为了实现它,可以简单的使用由Map定义的一个类集“视图”方法,如entrySet()或kegSet()方法。例如,可以获得关键字的一个集合“视图”,并遍历这些关键字。下面是采用这种技术后重新编写的程序。

*/

//Use iterators with a Hashtable.
import java.util.*;
class HTDemo2{
 public static void main(String[] args)
 {
  Hashtable balance = new Hashtable();
  String strName;
  double dblBal;

  balance.put("Sue Yuan",new Double(17.15));
  balance.put("Jiahui Sheng",new Double(78777));
  balance.put("Huajiang Chen",new Double(12345.77));
  balance.put("Magic Ya",new Double(-99.10));
  balance.put("Quanbing Chen",new Double(100.00));

  //Show all balances in hashtable.
  Set set = balance.keySet();   //get set-view of keys

  //get iterator
  Iterator i = set.iterator();

  //Display elements.
  while(i.hasNext()){
   strName = (String)i.next();
   System.out.println(strName  + ": " + balance.get(strName));
  }
  System.out.println();

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

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics