[JAVA]利用自定义关键字类取出HashTable中的关键字以及关键字的值。

由于上一遍文章提到的MyKey.java自定义类无法通过编译,因此直接导致本程序无法通过编译,我也是copy张老书上的,或许是张老师故意给我们一个陷阱,让我们自己去思考吧。

程序清单如下:HashTableTest.java

 

import  java.util. * ;

class  MyKey
{
        
private String name;
        
private int age;
        
public MyKey(String name,int age)
        
{
            
this.name = name;
            
this.age = age;
        }

        
        
public String toString()
        
{
            
return new String(name+" , "+age);
        }

        
        
public boolean equals(Object obj)
        
{   //覆盖equals方法
            if(name.equals(obj.name) && age==obj.age)
            
{
                
return true;
            }

            
else
            
{
                
return false;
            }

        }

        
        
public int hashCode()
        
{
            
//覆盖hashCode()方法
            return name.hashCode() + age;
        }

}


public   class  HashTableTest
{
    
public static void main(String[] args)
    
{
        Hashtable numbers 
= new Hashtable();
        numbers.put(
new MyKey("张三",23),new Integer(1));
        numbers.put(
new MyKey("李四",18),new Integer(3));
        numbers.put(
new MyKey("岳飞",100),new Integer(2));
        numbers.put(
new MyKey("孤独求败",88),new Integer(45));
    
//    Enumeration e = new Enumeration(); //Enumeration是接口类,不能实例化的
        Enumeration e = numbers.keys();
        
while(e.hasMoreElements())
        
{
            MyKey mk 
= (MyKey)e.nextElement();
            System.out.println(mk.toString() 
+ "=");
            System.out.println(numbers.get(mk).toString());
        }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值