Google Guava: How to use ImmutableSortedMap.naturalOrder?

拥有回忆 提交于 2019-12-23 21:19:40

问题


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();

回答1:


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();



回答2:


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)



来源:https://stackoverflow.com/questions/4906946/google-guava-how-to-use-immutablesortedmap-naturalorder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!