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.