Integer handling in Java vs. Ada
For those of you not in the loop, I attend a Diploma Programme in Computer Science in a school located in southern Denmark. The programming curriculum in the last couple of semesters have consisted mainly of courses in Java and Ada (and Spark, which, basically, is Ada with handcuffs).
Lately, I’ve grown more and more fond of Java, primarily for the following three reasons:
- The object (or class?) oriented paradigm suits me well, and this is very well implemented in Java.
- Sun’s Java API is as consistent and simple to use as it is vast and well documented.
- The garbage collection is brilliant and, as far as I have discovered, very well functioning.
But of course my fondness has a fly in the ointment. Java’s integer handling resembles those of many other programming languages, with the exception that the class Integer is a wrapper class for the primitive type int. But this particular area is, to say the least, ingeniously thought out in Ada, and I can’t help but miss this functionality when I’m coding in Java.
In Ada, creating a new integer-type with a delimited range for a specific purpose, is as simple as:
type My_Integer is new Integer range 26 .. 42;
And declaring an array with this new type as range, for instance, is even more trivial:
My_Array : array (My_Integer) of Some_Class;
This also works well with enumerated types:
type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
And, I assure you, doing the following declarations and assignments will very quickly become quite addictive:
Work_Day : constant array (Day) of Boolean := (Mon .. Fri => True, others => False); Consumed_Cups_Of_Coffee : array (Day) of Natural := (Mon => 10, Tue .. Fri => 7, Sun => 2, others => 3);
This is an immensely powerful feature, and I didn’t know I missed it in other languages before I tried it in Ada.
I don’t presume to know how this would be implemented in Java. I realize that this cannot be accomplished, simply by being able to inherit from the class Integer, as this merely wraps around the int-type, and thus would lack an integer type delimited to the suitable range.
But then what? Solving this pickle would surely make a lot of code a lot more elegant and readable. Any ideas are more than welcome.
