Christopher Smith
Christopher Smith

Reputation: 450

LinkedBlockingQueue peek at particular spot

I have a LinkedBlockingQueue and I want to check if there is a certain order of elements in the queue without removing the elements. I was hoping there was method I could use to peek at a particular spot in the queue. For example, queue.peekSpot(0) would return the head and quque.peekSpot(queue.size()) would return the tail. Right now I have this method but it removes the things it is reading. The queue is a type char by the way.

public boolean checkString(String string) {
    if (string.length() < 1) {
        return true;
    }
    char input = queue.take();
    if (input == string.charAt(0)) {
        return checkString(string.substring(1));
    }
    return false;
}

If I could use a peekSpot() method, this could be done as follows, greatly simplifying the code.

public boolean checkString(String string){
    for(int i = 0; i < string.length(); i++){
        if(!(string.charAt(i) == queue.peekSpot(i))){
            return false;
        }
    }
    return true;
}

Somebody might say, what if that spot doesn't exist? Well then it might wait for that spot to exist. I am using a queue instead of an ordinary string because this is a serial feed and the string would have to constantly change. Any ideas?

Upvotes: 0

Views: 575

Answers (1)

bitkot
bitkot

Reputation: 4504

There is no direct way to i.e access items by index. but You can call toArray(), which would return you an array and then you can access index locations. Something like this.

String peekSpot(Queue<String> queue, Integer index){
    if(queue == null){
        throw new IllegalArgumentException();
    }
    Object[] array = queue.toArray();
    return (String)array[index];
}

Upvotes: 1

Related Questions