I am currently rediscovering Java (working with Ruby a lot recently), and I love the compilation-time checking of everything. It makes refactoring so easy. However, I miss playing fast-and-loose with types to do an each
loop. This is my worst code.
Is this as short as it can be? I have a collection called looperTracks
, which has instances that implement Looper
. I don't want to modify that collection, but I want to iterate through its members PLUS the this
(which also implements Looper
).
List<Looper> allLoopers = new ArrayList<Looper>(looperTracks.length + 1);
for (LooperTrack track : looperTracks) {
allLoopers.add(track);
}
allLoopers.add(this);
for (Looper looper : allLoopers) {
// Finally! I have a looper
I'm particularly concerned about any features that are new to Java from 1.5 on that I may have missed. For this question I am not asking about JRuby nor Groovy, though I know that they would work for this.
Edit: Sorry (too much Ruby!)... looperTracks
is of type LooperTrack[]
and LooperTrack
implements Looper
.
You could at least use the fact that you can construct one collection using another as the base values. According to the docs:
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.
Which means that there is probably going to be room forthis
without having to do any resizing.
List<Looper> allLoopers = new ArrayList<Looper>(looperTracks);
allLoopers.add(this);
for (Looper looper : allLoopers) {
// Finally! I have a looper
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With