谁能告诉我JAVA的散列表(Hashtable)怎么用?

scorpionmxk 2003-03-16 10:30:39
哪位高手能告诉小弟我JAVA的散列表( Hashtable)具体怎么用,和链表有什么区别,谢谢了,小弟我E文不好,看文档看的不太明白。
...全文
254 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
star821116 2003-03-16
  • 打赏
  • 举报
回复
Hashtable内的作用跟HaspMap的作用相同,它们拥有相同的接口!Hashtable类的各个方法也是同步的!给你一个HaspMap的例子(散列映像):
import java.util.*;

/**
This program demonstrates the use of a map with key type
String and value type Employee.
*/
public class MapTest
{
public static void main(String[] args)
{
Map staff = new LinkedHashMap(101,0.75F,true);
staff.put("144-25-5464", new Employee("Angela Hung"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));

// print all entries

System.out.println(staff);

// remove an entry

staff.remove("567-24-2546");

// replace an entry

staff.put("456-62-5527", new Employee("Francesca Miller"));

// look up a value

System.out.println(staff.get("157-62-7935"));

// iterate through all entries

Set entries = staff.entrySet();
Iterator iter = entries.iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println("key=" + key + ", value=" + value);
}
}
}

/**
A minimalist employee class for testing purposes.
*/
class Employee
{
/**
Constructs an employee with $0 salary.
@param n the employee name
*/
public Employee(String n)
{
name = n;
salary = 0;
}

public String toString()
{
return "[name=" + name + ", salary=" + salary + "]";
}

/**
Sets the employee salary to a new value.
@param s the new salary.
*/
public void setSalary(double s)
{
salary = s;
}

private String name;
private double salary;
}
gdsean 2003-03-16
  • 打赏
  • 举报
回复
其实就是字典,用一个key来查找一个value
下面的例子表示用个数字字符串来做key,保存一些Integer对象在里面
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
下面表示如何用字符串key来取得Integer对象:

Integer n = (Integer)numbers.get("two");
if (n != null) {
System.out.println("two = " + n);
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧