您的位置:首页 > 编程语言 > Java开发

用java中的HashMap实现队列

2008-12-04 09:18 351 查看
 

import java.util.*;

public class VarCostRateQueue {

    private final static int size=20;

    private static HashMap storage=new HashMap(size);

    private static String[] keySet=new String[size];

    private static int head=-1,trail=-1;

    public VarCostRateQueue(){}

    public static void push(String key,Object obj)throws Exception

    {

        synchronized(storage)

        {

            synchronized(keySet)

            {

                if(storage.get(key)==null)

                {

                    trail=(trail+1)%20;

                    if(trail==head)

                    {

                        storage.remove(keySet[head]);

                        head=(head+1)%20;

                        storage.put(key, obj);

                        keySet[trail]=key;

                    }else

                    {

                        storage.put(key, obj);

                        keySet[trail]=key;

                        if(head==-1)

                            head=0;

                    }

                }

            }

        }

    }

    public static Object get(String key)throws Exception

    {

        return storage.get(key);

    }

    private static void clear()throws Exception

    {

        synchronized(storage)

        {

            storage.clear();

            head=-1;

            trail=-1;

        }

        

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hashmap java null