1

I am new to Java and trying to use:

public static ArrayBlockingQueue<String> qu=new ArrayBlockingQueue<>(900);
...
qu.enqueue(MyString);

or

public static Queue<String> qu=new Queue<>(900);
...
qu.enqueue(MyString);

Queue screams,claiming it's only an interface. ArrayBlockingQueue does not accept enqueue. I feel I'm making some basic mistake. My question is: do I have to write my own Queue implementing the interface every time I use it or is there a ready function? If yes, what am I doing wrong? My second question is: what is a standard queue size? From the specifications I've read I assumed it must be the maximum I may use but isn't 900 a bit big space-taker for a small application?

4

3 回答 3

2

您正在尝试创建一个接口的实例,而您应该实例化一个实现它的类。像这样:

public Queue<Integer> intQueue = new ArrayBlockingQueue<Integer>(10);

于 2013-07-12T21:34:18.467 回答
1

Here's what I'd recommend as a Queue member in a single-threaded application:

private final Queue<String> someLogicalName = new ArrayDeque<>();

Let's break this down.

The private modifier means that only the class (or instances of the class) in which this declaration appears can monkey with your queue.

The final modifier means that the member can't be reassigned. If you never plan to change the value, make that assumption explicit with the final modifier, and the compiler will tell you when you violate your assumption accidentally. And, if multiple threads will access the variable, making it final is one of the ways to obtain a guarantee that all threads will see its assigned value, rather than null.

I declare the variable as Queue, since that's the interface I want the code to work against. I don't declare it as the implementation class; this could prevent me from changing the implementation type later as my requirements change.

The name qu doesn't tell us anything. What if you have a few queues? Would you name them "qu", "qu2", "qu3"? That could quickly get confusing. Pick logical names that describe the role of the information in the variable, not its type.

How do I find an implementation class for Queue? Look at the documentation. See the section with the heading "All Known Implementing Classes?" Most of those are concrete types, and they fulfill the Queue interface. You can read the documentation for each of them to see what the differences are, and select the one appropriate for your use. While Queue has more implementations than most collection types, they follow naming patterns that make it easy to narrow down what you need. I picked a simple, single-threaded queue, but if you are working with a thread pool, you'll probably want a queue from the java.util.concurrent package.

The compiler can infer the type parameters for the constructor, so you can use the "diamond operator," <> to reduce clutter.

于 2013-07-12T21:58:43.133 回答
1

只需使用addandoffer而不是enqueue.

大小为 900 的数组很小,不值得担心。使用尽可能多的元素以允许队列容纳。

于 2013-07-12T21:23:48.627 回答