Channels ▼

Eric Bruno

Dr. Dobb's Bloggers

Java 7 - Spare Some Change?

February 13, 2012

Project Coin is a term used to describe a set of small changes to the Java language that make life easier for programmers. See the pun? The goal was to make minor tweaks to the language itself to make Java code easier to both write and read. In past blog postings, I've explored some of the deeper changes in Java 7, such as those involving InvokeDynamic, File IO, and concurrency. Let's take a quick glance at some other enhancements Java 7 provides.

Diamonds Are Java's Best Friend

Generics is one feature of the Java language that I find developers are quite divided on: Either you hate them or you love them. Most agree that the concept of templates is generally good, and when applied correctly, allow you to create elegant, reusable classes and code libraries. However, many feel Java's implementation of Generics misses the mark. Why? Because it's ugly! Let's explore.

Prior to Java 1.5, you would have declared and used a Map of Person objects with a string as the key like so:

    Map people = new HashMap();
    Person person = new Person("Bruno", "Eric");
    people.put("Bruno", person);
    Person me = (Person)people.get("Bruno");

See that cast on the last line? Without it this code won't compile. Not only does casting require more typing everywhere you use the Map classes, it leads to potential runtime errors as the compiler won't catch incorrect casts. For instance, replace the last line with:

    City city = (City)people.get("Bruno");

and your code will compile, but it will generate a ClassCastException at runtime. I know, in this example, it's obvious that casting an object from a Map named "people" to an object of type City is wrong, but in practice things aren't always this obvious.

Generics allow you to specify the types in the Map's declaration:

    Map<String, Person> people = new HashMap<String, Person>();
    Person person = new Person("Bruno", "Eric");
    people.put("Bruno", person);
    Person me = people.get("Bruno");

Subtle, but much better! Now it's clear what belongs in the Map, and what type the key is. It's also clearer to the compiler, which means you don't need to explicitly cast when getting or removing from the Map, and there's no chance for a ClassCastException. However, this syntax can quickly get out of hand. Consider the case of a Map of a Map, which itself uses Generics:

    Map<String, Map<Integer, String>> map = 
        new HashMap<String, Map<Integer, String>>();

Wow, that's ugly. Look closely and you'll notice that the type information is repeated: first in the declaration and again in the assignment. Java 7 introduced the "<>", called the Diamond operator, to alleviate this issue. Now, you can declare and assign the same Map of Map objects with much less typing:

    Map<String, Map<Integer, String>> map = 
        new HashMap<>();

This works for method returns as well:

    Map<String, Map<Integer, String>>  foo(/*…*/) {
        return new HashMap<>();

Flipping the Switch

I'm sure you've written code that needed to compare a given string to a few other strings. If so, it probably looked like this:

    if ( s.equals("first") )
    else if ( s.equals("second") )
    else if ( s.equals("third") )
        throw new Exception(/*…*/);

It would have been nice to instead use a switch statement to eliminate all of the verbose if..else code. Until Java 7, that wasn't possible. But now, you can finally do this:

    switch ( s ) {
      case "first":        doFirst();       break;
      case "second": doSecond(); break;
      case "third":      doThird();      break;
      default:              throw new Exception(/*…*/);   

It may not result in less typing, but the code is much easier to read, and it's more consistent in terms of writing comparison code.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.