我想创建一个Map<Long, Enum< ? extends SomeInterface>
。哪个是我最好的选择?
我试过这个
private Map<Long, Enum<? extends SomeInterface>[]> questionIdToanswersMapping = Collections.unmodifiableMap(Stream.of(
new SimpleEntry<>(QuestionEnum1.getQuestionId(), AnswerEnum1.values()),
new SimpleEntry<>(QuestionEnum2.getQuestionId(), AnswerEnum2.values()),
new SimpleEntry<>(QuestionEnum3.getQuestionId(), AnswerEnum3.values()),
new SimpleEntry<>(QuestionEnum4.getQuestionId(), AnswerEnum4.values()),
new SimpleEntry<>(QuestionEnum5.getQuestionId(), AnswerEnum5.values()))
.collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
但它正在提供错误&#34;无法从Map<Object,Object>
转换为Map<Long,Enum<? extends SomeEnum>[]>
&#34;。我是新来的。请帮忙!
我需要问题ID的不可修改的地图到相应的可能答案值。可能的答案是Enums
可能的答案包含如下:
public class RecognizedAnswers {
public enum AnswerEnum1 implements SomeInterface;
public enum Answer2 implements SomeInterface;
}
答案 0 :(得分:1)
我认为命名存在一个小问题:
你不能在java中扩展一个枚举,使用所需方法的接口,如下面的
以下代码工作正常:
@Test
public void test() {
Map<Long, Enum<? extends SomeEnum>[]> questionIdToanswersMapping = Collections.unmodifiableMap(Stream.of(
new AbstractMap.SimpleEntry<>(QuestionEnum1.A.getQuestionId(), AnswerEnum1.values()),
new AbstractMap.SimpleEntry<>(QuestionEnum1.B.getQuestionId(), AnswerEnum1.values()),
new AbstractMap.SimpleEntry<>(QuestionEnum1.C.getQuestionId(), AnswerEnum2.values()),
new AbstractMap.SimpleEntry<>(QuestionEnum1.D.getQuestionId(), AnswerEnum2.values())
)
.collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
System.out.print(questionIdToanswersMapping.size());
}
enum QuestionEnum1 {
A, B, C, D;
Long getQuestionId() {
return (long) name().hashCode(); // my mocked values
}
}
interface SomeEnum {
}
enum AnswerEnum1 implements SomeEnum {
}
enum AnswerEnum2 implements SomeEnum {
}
答案 1 :(得分:0)
我试图复制你的例子(因为你混淆了枚举类型,我自己做了)并且看起来编译得很好:
enum SomeEnum { FOO, BAR }
private Map<Long, Enum<? extends SomeEnum>[]> exampleMap =
Collections.unmodifiableMap(Stream.of(
new SimpleEntry<>(1L, SomeEnum.values()))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)));
我的猜测是你有一个缺失的括号,或者你的QuestionEnum1.getQuestionId()
返回一个int
而不是long
,这些东西让编译器感到困惑,以至于它可以&#39 ; t给出明确的错误信息。
我注意到Stream API实际上并不是构建常量映射的简洁方法。简单地构建这样的地图&#34;通常&#34;使用Map.put()
可能更简单,更容易阅读,即使它需要static {}
块或辅助函数。您可以使用Guava immutable collections做得更好,可以这样使用:
private final ImmutableMap<Long, Enum<? extends SomeEnum>[]> questionIdToanswersMapping =
ImmutableMap.builder()
.put(QuestionEnum1.getQuestionId(), AnswerEnum1.values())
.put(QuestionEnum2.getQuestionId(), AnswerEnum2.values())
.put(QuestionEnum3.getQuestionId(), AnswerEnum3.values())
.put(QuestionEnum4.getQuestionId(), AnswerEnum4.values())
.put(QuestionEnum5.getQuestionId(), AnswerEnum5.values())
.build();
更清晰,更容易阅读(和写作)。