【发布时间】:2020-04-19 04:20:09
【问题描述】:
我知道标题很奇怪,我不知道还能写什么。我对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
}
}
【问题讨论】:
-
只是一个问题....为什么要遍历空地图?如果您刚刚创建了新的 myMap 对象,它将没有任何元素
-
为什么需要
MyMap类。为什么不直接使用LinkedHashMap<MyType,MyType>? -
@TheOni 这只是一个例子。这些不是实际的课程。有一个类是相似类型的库。 MyMap 和 MyType 是库类。
-
@Eran 有一个库,它有自己的类型,类似于 MyMap。它有一个方法,我使用它返回 MyMap。因此我只能决定如何使用它,而不是对现有库进行更改。