This is in addition to Torben's answer.
Java Collections Framework
It was a good idea to replace the original array with an ArrayList
, but you can get even more benefit from that replacement.
Your size
field isn't necessary any more, as there is a size() method in the collections framework, and what you count yourself is exactly the size of your list, so you can use that method and delete the size
field.
You declare the list as
private ArrayList<Item> a;
It's recommended to declare fields and variables with the least specific interface type that matches your needs. Candidates are Collection
and List
. Collection
doesn't support the indexed access that you need, so you should write
private List<Item> a;
or even include the initialization there instead of the constructor:
private List<Item> a = new ArrayList<>();
This way, it's easier to later change e.g. from an ArrayList
to a LinkedList
if you see a benefit, or want to do performance comparisons. As both classes fully comply with the List
interface, no other line of code has to be touched for that change.
You might even decide to make your own class conform to the Collections framework by declaring to implement Collection
or one of its sub-interfaces. This makes such a queue class much more useful than its "isolated" counterpart.
But be warned that there is some complexity in implementing a compliant Collection
from scratch, so the recommended way would be to extend some existing class, maybe AbstractList
or AbstractQueue
.
Style
Your indentation is perfect.
Your naming can be improved (see Torben's answer).
Your usage of spaces is a bit inconsistent and not following the conventions we all are used to see, e.g. in
}else {
Your IDE surely has a function for re-formatting your code (if not, switch to decent one, e.g. Eclipse), and you should make it a habit to let it do its job regularly.
Documentation
This class could well become part of a useful library. Then it's important to let your fellow developers know what the various methods do. While it's quite possible to guess what enqueue()
and dequeue()
do (good naming!), at least your sample()
method isn't self-explanatory from its name, and deserves a documentation.
You should make it a habit to write Javadoc-formatted comments for classes, constructors and public methods so others can read what they are meant for, without having to dive into your source code. The Javadoc format is well supported in all decent IDEs, e.g. showing up as a tooltip on method names.