How-To: Initialise arrays of objects in Java

You might think, like I did, that if you create an array of objects in Java then the constructor is automatically called on each object as part of the array creation process. But you’d be wrong.

Creating an array merely creates the object references – you have to instantiate each “inner” object in the array as a separate step if you want to be able to, ya know, do stuff… I think this is because in Java an array is an object – like, quite literally a single object that can be passed around like a single thing.

An example, perhaps?

Person Class

PersonTestDrive Class

How-To: Get human-friendly dates in Java using the Calendar class

ISO-8601 has a PosseAs part of the groundwork for some upcoming Java shenanigans I’ve finished off reading/skimming Head First Java – and it’s a truly excellent book. I wish it covered Connector/J & MySQL, but I can find that knowledge elsewhere so it’s not that big of a deal.

As part of today’s prep I ended up writing something I didn’t think I’d have to – a function to get a nice, human-readable date as a String. I don’t like having to write things like this because surely getting a nice, human-readable version of what’s essentially a timestamp (if the Date class wasn’t deprecated) has been solved. By which I mean that it’s done – let’s never, ever solve that same problem again. But the issue is that if you don’t know where to look for the solution, then it can take you longer to find it than to solve the problem again, and I think that’s what’s happened to me today when I didn’t feel like learning and using the joda-time API to do something I felt core Java should be capable of.

Before we get to the source code I’d just like to direct a quick word to to the Java API Calendar class developers to say:

  • I don’t care who you worship – the first day of the week is Monday, please see ISO-8601, and
  • Chopping and changing between zero-based constants and one-based constants sucks massive d*cks.

Anyways, the getFriendlyDate function gets a day/month/year from a Calendar object and converts it into something a human being might like to read, like this…

And the source code to perform this scandalous transformation is:

Update 13-Oct-2011: Just realised that the 1st, 2nd, 3rd etc. stuff is broken because I’m checking the last digit in the day of month and using that, so if it ends with 3 I give the suffix “rd” making it “3rd”, which is fine until you get to the 13th, which comes out as “13rd”… I don’t have time to fix it up right now, but I will in the near future. Or do a total re-write using the mighty Shetboy’s formatting advice (see comments).

Cheers!

Java enhanced for-loop FTW

I’ve got to do a whole slab of Java/J2EE coding soon so I’m in the process of skimming/re-acquainting myself with the Java language as a whole, when I just came across the new way to iterate over collections in a for-loop (available from Java 5 onwards) – and it’s genius!

How much easier to both read and write is that? Clever clever clever…

P.S. I just looked it up and Java 5 was released in 2004, and it’s only now I’m finding out about this?! Hahaha! Besides a socket client I knocked together a couple of months back I haven’t coded anything in Java since 2001!

Update 2014: Whilst very useful in general, avoid the enhanced for-loop in game development; it creates temporary objects which the garbage collector must then clean up. Any time the GC runs, you’ll take a performance hit. For example, if you’re writing a game and you use a lot of these, your game’s frame rate may stutter as and when the GC reclaims memory (which is as and when it feels like running – you may ask it to run, but whether it does or not is outside of your control).

Android dev is easy!

Well, kinda. It’s certainly easy to get up and running with the Android SDK and Eclipse with the ADT Plugin (Android Development Tools), as long as you know a little Java. Even the GUI stuff is all drag-and-drop, which I really quite liked.

To knock together a quick celcius<–>fahrenheit converter (from never having developed on Android to installing the tools and being up and running in less than an hour):

  1. Read this
  2. …which guides you step-by-step on how to build this:

    Android - App in Menu

    Android Temperature Conversion App

This has got me wondering how easy it is to integrate OpenGL ES into an Android app, which would be a pretty spiffy weekend project I reckon…

An example implementation of the Strategy design pattern in C++

A mate put me on to the book Head First Design Patterns the other day, and it’s excellent, so I’ve been reading away and coding up the examples. The examples themselves are in Java, but I’m more interested in C++ so I’m transcoding them as I go (pun!).

The Strategy pattern aims to give separate implementations of algorithms (in other words – functions) to different subclasses of your major class, and allow you to change the behaviour at run-time, rather than have it hard-coded at compile-time. Pretty neat.

Now for the ducks…

Which gives the output:

I’m a real mallard duck!
The duck bobs peacefully on the surface of the water.
The duck flies into the friendly skies!
The duck says: Quack!

I’m a rubber-ducky!
The duck bobs peacefully on the surface of the water.
I can’t fly!
The duck says: <<< Silence >>>

I’m a painted wooden duck!
The duck bobs peacefully on the surface of the water.
I can’t fly!
Changing fly behaviour…
The duck flies through the air using a rocket!
The duck says: <<< Silence >>>
Changing quack behaviour…
The duck says: Quack!

Update 24th Nov 2012: ijab points out in the comments below that this code contains memory leaks, and yup it does – so I’ve provided a version with the memory leaks fixed in my reply below, but have deliberately left the original version above to keep things focused. All you really need to do avoid leaking memory is:
– Have virtual destructors for the xxxBehaviour classes (they don’t have to do anything special, but they need to exist or the compiler will give you warnings),
– Delete the existing behaviour before creating and applying a new one (maybe only delete if they’re not null – you choose), and
– Don’t forget to delete your ducks at the end of the program!