本帖最后由 戴振良 于 2012-3-27 22:18 编辑
- import java.util.Hashtable;
- import java.util.Enumeration;
- class TestHashtable {
-
- public static void main(String[] args) {
- Hashtable ht = new Hashtable();
- ht.put(new Keys("张三",25),new Integer(1));
- ht.put(new Keys("李四",20),new Integer(2));
- ht.put(new Keys("王五",89),new Integer(3));
-
- Enumeration e = ht.keys();
- while(e.hasMoreElements()) {
- Keys keys = (Keys)e.nextElement();
- System.out.print(keys + ": ");
- System.out.println(ht.get(keys)); //取出键(keys)对应的值,并打印到屏幕
- }
- }
- }
- class Keys {
-
- private String name = null;
- private int age = 0;
-
- public Keys(String name,int age) {
- this.name = name;
- this.age = age;
- }
- public boolean equals(Object obj) { //覆盖equals方法
- if(!(obj instanceof Keys))
- return false;
- return age == ((Keys)obj).age && name.equals(((Keys)obj).name);
- }
- public int hashCode() { //覆盖hashCode方法
- return name.hashCode() + age;
- }
-
- public String toString() { //覆盖toString方法
- return name + "," + age;
- }
- }
复制代码 输出结果为:
王五,89: 3
李四,20: 2
张三,25: 1
为什么这个输出的顺序不是:张三,李四,王五呢?我放的时候是按这个顺序放的呀! |