英文:
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<String, String> entries1 = stringRedisTemplate.opsForHash().entries(key);
// This is OK.
HashOperations<String, String, String> opsForHash = stringRedisTemplate.opsForHash();
Map<String, String> 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 <HK, HV> HashOperations<K, HK, HV> opsForHash()
If you want to use a single line, you need to set the generics, just like:
Map<String, String> entries1 = stringRedisTemplate.<String, String>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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论