A fast queue in Java

前端 未结 5 1722
余生分开走
余生分开走 2021-02-04 00:59

I am looking for a fast queue implementation in Java. I see that LinkedList implements the Queue interface, but it will only be as fast as

5条回答
  •  执笔经年
    2021-02-04 01:19

    Start with really simplistic rotating Queue implementation with "C/C++ like" attitude and fixed size.

    class SimpleQueue
    {
    
    int index   = 0;
    int head    = 0;
    int size    = 100;
    int counter = 0;
    E[] data    ;
    
    
    @SuppressWarnings("unchecked")
    SimpleQueue()
    {
        data = (E[]) new Object[size];
    }
    
    public void add(E e)
    {
        data[index]=e;
        index=(index+1)%size;
        counter++;
    }
    
    public E poll()
    {
        E value = data[head];
        head=(head+1)%size;
        counter--;
        return value;
    }
    
    public boolean empty()
    { return counter==0; }
    
    //Test
    public static void main(String[] args)
    {
        SimpleQueue s = new SimpleQueue();
    
        System.out.println(s.empty());
    
        for(int i=0; i< 10; i++)
            s.add(i);
    
        System.out.println(s.empty());
    
        for(int i=0; i<10; i++)
            System.out.print(s.poll()+",");
    
        System.out.println("\n"+s.empty());
    
    }
    }
    

    And then improve it.

提交回复
热议问题