用java中的HashMap实现队列

 
  1. import java.util.*;
  2. public class VarCostRateQueue {
  3.     private final static int size=20;
  4.     private static HashMap storage=new HashMap(size);
  5.     private static String[] keySet=new String[size];
  6.     private static int head=-1,trail=-1;
  7.     public VarCostRateQueue(){}
  8.     public static void push(String key,Object obj)throws Exception
  9.     {
  10.         synchronized(storage)
  11.         {
  12.             synchronized(keySet)
  13.             {
  14.                 if(storage.get(key)==null)
  15.                 {
  16.                     trail=(trail+1)%20;
  17.                     if(trail==head)
  18.                     {
  19.                         storage.remove(keySet[head]);
  20.                         head=(head+1)%20;
  21.                         storage.put(key, obj);
  22.                         keySet[trail]=key;
  23.                     }else
  24.                     {
  25.                         storage.put(key, obj);
  26.                         keySet[trail]=key;
  27.                         if(head==-1)
  28.                             head=0;
  29.                     }
  30.                 }
  31.             }
  32.         }
  33.     }
  34.     public static Object get(String key)throws Exception
  35.     {
  36.         return storage.get(key);
  37.     }
  38.     private static void clear()throws Exception
  39.     {
  40.         synchronized(storage)
  41.         {
  42.             storage.clear();
  43.             head=-1;
  44.             trail=-1;
  45.         }
  46.         
  47.     }
  48. }

你可能感兴趣的:(Algorithm)