我知道标题很奇怪,我不知道还能写些什么。我对java比较陌生,所以如果这是非常基本的东西,我很抱歉。我已经尽了最大努力通过代码来解释这一点。问题是-
这是汇编的,
// WAY 1
Map<MyType, MyType> myMap = (Map) new MyMap();不是这样的,
// WAY 2
Map<MyType, MyType> myMap2 = (Map<MyType, MyType>) new MyMap();首先,为什么会有这样的行为。其次,方法2允许我将我想要的代码写在用WhatIWant方法编写的一行代码中,而方法1则不像在方法WhatIWant中所写的那样。我能把代码写成一行吗?如果是的话怎么做。若否,原因为何。
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
// A class not created by me but in a library so i cannot use generic types as i cannot change stuff here
class MyMap extends LinkedHashMap<Object, Object> {
}
// has methods which i need for processing on myMap
class MyType {
int myMethod() {
return -1;
}
}
class Scratch {
public static void main(final String[] args) throws Exception {
// WAY 1:
// compiles
// WARNING : Unchecked assignment: 'java.util.Map' to 'java.util.Map<MyType, MyType>'
Map<MyType, MyType> myMap = (Map) new MyMap();
// WAY 2:
// does not compile
// ERROR: Inconvertible types; cannot case 'MyMap' to 'java.util.Map<MyType, MyType>'
Map<MyType, MyType> myMap2 = (Map<MyType, MyType>) new MyMap();
}
public static void WhatIWant() {
// to be able to write code below in one line
Map<MyType, MyType> myMap = (Map) new MyMap();
myMap.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toString(),
entry -> entry.getValue().myMethod()
));
// I thought it would work if i used WAY 2 like
((Map<MyType, MyType>) new MyMap()).entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toString(),
entry -> entry.getValue().myMethod()
));
// but as you saw above in WAY 2, it does not compile, how can i do this in one line
}
}发布于 2019-12-30 12:11:33
如果您希望它在“一行”(又名1语句,5行)中,双转换 it:
((Map<MyType, MyType>) (Map) new MyMap()).entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toString(),
entry -> entry.getValue().myMethod()
));第一个强制转换使用原始Map,因此丢弃<Object, Object>泛型类型参数。这对于向后兼容性是有效的,但确实会生成一个编译器警告,说明您不应该这样做:
Map是原始类型。对泛型类型Map<K,V>的引用应该参数化。
然后,第二个强制转换应用一组新的泛型类型参数。这对于向后兼容性是有效的,但是会生成一个编译器警告,说明您是独立的,因为泛型参数类型是不强制的:
类型安全:未检查的从
Map到Map<MyType,MyType>的转换
不能直接转换的原因是因为Map<MyType,MyType>不是Map<Object,Object>的一个子类型,也就是说,它在Map<Object,Object>类型系统中是不可能的。请参阅Is List a subclass of List? Why are Java generics not implicitly polymorphic?
发布于 2019-12-30 12:18:15
您需要在您的类中进行一些更改才能解决问题。
// instead Object use your own type
class MyMap extends LinkedHashMap<MyType, MyType> {
}现在,您可以直接访问/执行way 2,而无需强制转换:
Map<MyType, MyType> myMap2 = new MyMap();在这里也是如此:
new MyMap().entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toString(),
entry -> entry.getValue().myMethod()
));https://stackoverflow.com/questions/59530510
复制相似问题