Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Language Tricks to Shorten My Java Code? [closed]

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.

like image 495
Dan Rosenstark Avatar asked Feb 01 '10 12:02

Dan Rosenstark


1 Answers

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
like image 169
Yacoby Avatar answered Oct 01 '22 07:10

Yacoby