java中静态泛型方法调用可以参考google ImmutableMap的方法调用ImmutableMap.<String, Integer>builder() 而不是ImmutableMap<String, Integer>.builder()。前者是表示静态方法的调用,后者表示要调用ImmutableMap<String, Integer>示例的build方法,是和类定义想违背的。
import com.google.common.collect.ImmutableMap;
public class ImmutableMapDemo {
public static void main(String[] args) {
// Create an ImmutableMap using the builder pattern
ImmutableMap<String, Integer> immutableMap = ImmutableMap.<String, Integer>builder()
.put("One", 1)
.put("Two", 2)
.put("Three", 3)
.build();
// Print the immutable map
System.out.println("Immutable Map: " + immutableMap);
// Attempting to modify the map will result in an UnsupportedOperationException
// immutableMap.put("Four", 4); // Uncommenting this line will result in an exception
// Accessing values
int valueForKeyTwo = immutableMap.get("Two");
System.out.println("Value for key 'Two': " + valueForKeyTwo);
// Attempting to modify the map will result in an UnsupportedOperationException
// immutableMap.remove("Three"); // Uncommenting this line will result in an exception
}
}
public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
public static <K, V> ImmutableMap.Builder<K, V> builder() {
return new ImmutableMap.Builder();
}
}
The syntax
ImmutableMap<String, Integer>.builder()
is not used becausebuilder()
is a static method of theImmutableMap
class, and it does not depend on the generic type parameters of theImmutableMap
instance. Instead, it returns a builder object that is independent of the specific types of theImmutableMap
it will build.When you write
ImmutableMap.<String, Integer>builder()
, you are using the static methodbuilder()
from theImmutableMap
class to create a builder object. The generic type parameters<String, Integer>
are specified to indicate the types of keys and values that the resultingImmutableMap
will have.If you were to use the syntax
ImmutableMap<String, Integer>.builder()
, it might imply that you are trying to call a non-static method on an instance ofImmutableMap
, butbuilder()
is a static method used for creating a new builder instance.In summary, the typical usage is
ImmutableMap.<String, Integer>builder()
to make it clear that you are invoking a static method to create a builder with specific type parameters. If you're using Java 7 or later, you can use the diamond operator (<>
) to simplify the syntax, as shown in the previous example.