Jul 31

It seems that in almost every system I write has a bi-directional containment. For example, a Table instance containing Column instances that should know to reference back to the Table instance containing them. Sometimes, when writing an API that uses these kind of tables and columns and allows the user of the API to define them, type safety using Generics is wanted.


Let’s look at the non-Generic case first:


public interface Table {
  Collection getColumns();
}

public interface Column {
  Table getTable();
}

However, as said in the beginning of the post, we want Table to know which specific Column it is containing. So, we’ll define Table as Table<TColumn>:
Continue reading »

Share/Save/Bookmark

Feb 27

Autoboxing, a feature which seems like it had squeezed into JSR 201, is a convenience feature which has its own bag of tricks. This feature seems to come as a complement to the major EoD feature in Tiger, Generics. Since generics can’t be used with primitives as their types (i.e. Can’t declare Collection<int>), their wrappers are used instead (Collection<Integer>). This is due to erasure, as most annoying things about generics are (such as reflection data, an old rant of mine).

It’s obvious to see how autoboxing provides ease of use: Just taking foo(Integer num) as an example, the difference between foo(5) and foo(new Integer(5)) is notable! To take another case as an example, a call to bar(Integer[] arr) is simplified, using the varags feature, from bar(new Integer[] { new Integer(1), new Integer(2), new Integer(3) }) to bar(1, 2, 3), so the ease of development provided by this feature is nothing to ignore.

There are things that are less obvious about this new feature, though:

Continue reading »

Share/Save/Bookmark

Feb 24

We all know how to use enums - Ordinal values and even their textual names are now accessible. Heck, we can even iterate over all of them, eliminating the need of the old-fashioned C++ “START” and “END” values.

Enums are much more though. Java implements enums as full-fledged classes:

  • They have constructors, they have methods and they have fields.
  • They are treated specially in switch statements to make them more efficient.
  • They have special classes that allows enums to be used as bit-flags, and to be used efficiently when mapping values.

Enums as Classes

When you write a new enum, you are actually creating a class containing static instances of itself - The enum values. The class will extend the class Enum (discussed earlier for its weird generification), and every instance will be initialised with a String - the name of the enum value - and an integer - the enum’s ordinal value.
So, for example, the following enum:
Continue reading »

Share/Save/Bookmark

Chaotic Java is Digg proof thanks to caching by WP Super Cache!