这两段代码之间有什么区别吗?

huangapple go评论67阅读模式
英文:

Is there any difference between these two codes?

问题

@Autowired
private StringRedisTemplate stringRedisTemplate;

public void test(String key) {
    // IDEA提示错误
    Map<String, String> entries1 = stringRedisTemplate.opsForHash().entries(key);
        
    // 这是正确的。
    HashOperations<String, String, String> opsForHash = stringRedisTemplate.opsForHash();
    Map<String, String> entries = opsForHash.entries(key);  
}
英文:
@Autowired
private StringRedisTemplate stringRedisTemplate;

public void test(String key) {
    // IDEA prompts an error
    Map&lt;String, String&gt; entries1 = stringRedisTemplate.opsForHash().entries(key);
        
    // This is OK.
    HashOperations&lt;String, String, String&gt; opsForHash = stringRedisTemplate.opsForHash();
    Map&lt;String, String&gt; entries = opsForHash.entries(key);  
}

答案1

得分: 4

问题是方法opsForHash()使用了两种泛型,签名如下:

public <HK, HV> HashOperations<K, HK, HV> opsForHash()

如果你想要在一行中使用,你需要设置这些泛型,就像这样:

Map<String, String> entries1 = stringRedisTemplate.<String, String>opsForHash().entries(key);

在你的代码中,第二种方法有效是因为编译器从=操作符左边定义的变量中推断出了泛型。

英文:

The problem Is that the method opsForHash() uses 2 generics, This is the signature:

public &lt;HK, HV&gt; HashOperations&lt;K, HK, HV&gt; opsForHash()

If you want to use a single line, you need to set the generics, just like:

Map&lt;String, String&gt; entries1 = stringRedisTemplate.&lt;String, String&gt;opsForHash().entries(key);

In your code, the second approach works because the compiler finds out the generics from the defined variable on the left side of the = operator.

huangapple
  • 本文由 发表于 2020年9月29日 19:00:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64118241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定