1

I have an ArrayBlockingQueue declared like this:

private BlockingQueue<E> queue = new ArrayBlockingQueue<E>();

now I have to access to a specific element of this queue. I have a method

public E takeElement(int j)
{
       //some code
}

and I have to take the j-element of the queue. How can I do that?? thx

3
  • 1
    If you need indexed access, why are you using a BlockingQueue? Its intended usage is processing items in order, with the possibility of waiting (blocking) if the queue is empty. Commented Feb 4, 2015 at 9:18
  • I have a queue and some method... somethimes I have to take head-element, somethimes I have to take j element. Commented Feb 4, 2015 at 9:27
  • What is the problem that you are really trying to solve? You don't need to use BlockingQueue in a way that it was never meant to be used: You need a different data structure/algorithm that solves some problem. What is the problem? Commented Feb 4, 2015 at 14:55

2 Answers 2

2

You could write:

E element = (E) queue.toArray()[j];

This will probably give a warning, but that is safe to ignore.

Sign up to request clarification or add additional context in comments.

4 Comments

thx. Now I have the opposite question... what I have to do if I have to put an element in j-position??
You can't. If you need access like this, you shouldn't be using a Queue. Consider ArrayList instead.
I do this but I'm not sure that is a thread-dafe operation: queue.toArray()[j] = element;
Assinging an element to the array has no effect on the Queue.
0

try this

public E takeElement(int j) {
    for(int i = 0; i < j; i++) {
        E e = queue.poll();
        if (i == j - 1) {
            return e;
        }
    }
    return null;
}

or iterator based version:

public E takeElement(int j) {
    Iterator<E> it = queue.iterator();
    for(int i = 0; it.hasNext() && i < j; i++) {
        E e = it.next();
        if (i == j - 1) {
            return e;
        }
    }
    return null; 
}

4 Comments

This would remove all elements in front of the sought element. I don't think that's what OP is looking for. Granted, it does adhere better to the purpose of Queue.
Poll remove all head element, I don't want this.
You really should be using a List. Just type list.get(0); when you need the head element.
It's a bit funny when a 57.2k user posts an answer that gets auto-flagged as Low Quality. Try explaining your answer a bit more in the future and it won't have to show up in LQ-queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.