3

I'm using Google Guava r08 and JDK 1.6.0_23.

I want to create an ImmutableSortedMap using a builder. I know I can create the builder like this:

ImmutableSortedMap.Builder<Integer, String> b1 =
    new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural());

and then use that to build maps, for example:

ImmutableSortedMap<Integer, String> map =
    b1.put(1, "one").put(2, "two").put(3, "three").build();

I noticed that class ImmutableSortedMap has a method naturalOrder() that returns a Builder with natural ordering. However, when I try to call this method, I get strange errors. For example, this gives a strange "; expected" error:

// Does not compile
ImmutableSortedMap.Builder<Integer, String> b2 =
    ImmutableSortedMap<Integer, String>.naturalOrder();

What is the correct syntax to call the naturalOrder() method?

The API documentation of the method mentions some compiler bug. Does that have anything to do with this method not working?

edit

MForster's answer is good. But when leaving off the generics, I can't do it "in one go":

// Doesn't work, can't infer the types properly
ImmutableSortedMap<Integer, String> map =
    ImmutableSortedMap.naturalOrder().put(1, "one").put(2, "two").put(3, "three").build();

This does work:

ImmutableSortedMap<Integer, String> map =
    ImmutableSortedMap.<Integer, String>naturalOrder().put(1, "one").put(2, "two").put(3, "three").build();
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 1
    Yes, if you build the whole map in one series of chained calls, you do have to put `ImmutableSortedMap.naturalOrder()`. Java is unable to infer the type arguments of the `naturalOrder()` call since the `Builder` it returns isn't ever assigned to anything. – ColinD Feb 05 '11 at 15:14

2 Answers2

11

The correct syntax is

ImmutableSortedMap.Builder<Integer, String> b2 =
    ImmutableSortedMap.<Integer, String>naturalOrder();

And you can drop the generics altogether, because they are inferred in this case:

ImmutableSortedMap.Builder<Integer, String> b2 =
    ImmutableSortedMap.naturalOrder();
MForster
  • 8,806
  • 5
  • 28
  • 32
  • Ah, it's that simple! Thanks. – Jesper Feb 05 '11 at 13:07
  • 3
    More information about the "ImmutableSortedMap.naturalOrder()" syntax: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ402 (explicit type argument specification) – Etienne Neveu Feb 05 '11 at 13:29
5

The correct syntax should be:

ImmutableSortedMap.Builder<Integer, String> b2 =
ImmutableSortedMap.<Integer, String>naturalOrder();

(Note that the generic parameters are behind the dot, not before)

Boris
  • 4,327
  • 2
  • 19
  • 27