HashMap,有点不对劲

时间:2012-10-22 13:31:42

标签: java hashmap

我有一个HashMap:

public static HashMap<Long, KeepAliveTimer> kaTimer;

它存储MACAddress和Timer。

我创建了HashMap:

   if(kaTimer == null) {
        //init the Hash
        kaTimer = new HashMap<Long, keepAliveTimer>();
        KeepAliveTimer keepAliveTimer = new KeepAliveTimer(macaddress, ipaddress); 
        kaTimer.put(macaddress, keepAliveTimer);
    } else {
                    //The Hash exists
        if(kaTimer.containsKey(macaddress)) {
            //The MAC exists into the map
            System.out.println(kaTimer.size());
            Collection col = kaTimer.values();
            for (Object obj : col) {
                      System.out.println(obj);
            }

            System.out.println(String.valueOf(macddress));

            KeepAliveTimer keepAliveTimer = kaTimer.get(macaddress);
            keepAliveTimer.update();
        } else {
            //The MAC doesn't exist in the Hash
            KeepAliveTimer keepAliveTimer = new KeepAliveTimer(macddress, ipaddress); 
            kaTimer.put(macaddress, keepAliveTimer);
        }

    }

KeepAliveTimer:

public KeepAliveTimer(long mac, String ipAddress){
    this.macaddress = mac;
    this.ip = ipAddress;

    timer = new Timer();

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            timerFinished();

        }
    };
    log.info(String.valueOf(macaddress) + " con la ip " + ip);
    timer.schedule(timerTask, 3*60*1000);
}


public void update() {

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            timerFinished();

        }
    };
    log.info(String.valueOf(macaddress) + " con la ip " + ip);
    timer.cancel();
    timer.purge();
    timer = new Timer();
    timer.schedule(timerTask, 3*60*1000);
}

public void timerFinished() {

    KeepAlive keep = new KeepAlive(macddress, ip);
    keep.removeFromHash();
     //Actions
}

当创建KeepAliveTimer元素时,一切正常,我创建了2个KeepAliveTimer元素:

 KeepAliveTimer keepAliveTimer = new KeepAliveTimer(macddress, ipaddress); 
 kaTimer.put(macaddress, keepAliveTimer);

当创建所有这些元素时,我必须使用KeepAliveTimer元素,因此,我从Hash中提取它们:

 KeepAliveTimer keepAliveTimer = kaTimer.get(macaddress);
 keepAliveTimer.update();

每个元素都是使用mac和ip创建的,但是在提取最后创建的ip时总是使用

我添加了一行:

System.out.println(kaTimer.size());
Collection col = kaTimer.values();
for (Object obj : col) {
    System.out.println(obj);
}

System.out.println(String.valueOf(macddress));

我得到了:

//First element
//In the HashMap
spb.KeepAliveTimer@105bd58
spb.KeepAliveTimer@edf3f6
//MAC
26954208388119
//KeepAliveTimer I get
spb.KeepAliveTimer@edf3f6
//MAC + IP
INFO: 26954208388119 con la ip 178.139.7.27

//Second element
//In the HasMaP
spb.KeepAliveTimer@105bd58
spb.KeepAliveTimer@edf3f6
//MAC
26954208388118
//Timer I get
spb.KeepAliveTimer@105bd58
//MAC+IP
INFO:  26954208388118 con la ip 178.139.7.27

0 个答案:

没有答案