java 静态泛型方法调用

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 because builder() is a static method of the ImmutableMap class, and it does not depend on the generic type parameters of the ImmutableMap instance. Instead, it returns a builder object that is independent of the specific types of the ImmutableMap it will build.

When you write ImmutableMap.<String, Integer>builder(), you are using the static method builder() from the ImmutableMap class to create a builder object. The generic type parameters <String, Integer> are specified to indicate the types of keys and values that the resulting ImmutableMap 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 of ImmutableMap, but builder() 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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值