Language Tricks to Shorten My Java Code?

collections, java, syntax

Solution

There are at least two possible built-in ways to shorten your code:

You could use Collection.addAll(Collection) that appends each element in the collection passed as parameter to the end of the collection.:

List<Looper> allLoopers = new ArrayList<Looper>();

...

allLoopers.addAll(looperTracks);
allLoopers.add(this);

for(Looper looper : allLoopers) {
  ...
}

or you can use a constructor that takes a collection as a parameter:

List<Looper> allLoopers = new ArrayList<Looper>(looperTracks);

Due to the change of question: All arrays can easily be converted to collections using java.util.Arrays e.g.

List<Looper> someLooperTracks = Arrays.asList(looperTracks). 

This will wrap the array in a fixed-size list.

Problem

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`.

Original source