[英]Java generics - generic method doesnt compile
Hi I have a class SomeClass and a private map that I want to have in values list of objects A and B where B extends A. 嗨,我有一个类SomeClass和一个私有映射,我希望在对象A和B的值列表中拥有这些对象,其中B扩展了A。
The below code doesnt compile.. I cant change anything in class name, it must be left like: 下面的代码无法编译..我无法更改类名称中的任何内容,必须将其保留为:
public class SomeClass {
<T extends ParentObject> Map<SignedOperationNameEnum, List<T>> operationToOrderStateSkipSignatureSetMap = new HashMap<>();
}
After class's name definiton 上课后的名字definiton
public class SomeClass<T extends ParentObject> {
Map<SignedOperationNameEnum, List<T>> operationToOrderStateSkipSignatureSetMap = new HashMap<>();
}
You should change your code to: 您应该将代码更改为:
public class SomeClass<T extends ParentObject> {
Map<SignedOperationNameEnum, List<T>> operationToOrderStateSkipSignatureSetMap = new HashMap<>();
}
It depends on java version which u are using. 这取决于您使用的Java版本。 If u are using java 1.7 or higher, then u can use: 如果您使用的是Java 1.7或更高版本,则可以使用:
public class SomeClass<T extends ParentObject> {
Map<SignedOperationNameEnum, List<T>> operationToOrderStateSkipSignatureSetMap =
new HashMap<>();
}
If u have 1.6 or earlier, then: 如果您的1.6或更早版本,则:
public class SomeClass<T extends ParentObject> {
Map<SignedOperationNameEnum, List<T>> operationToOrderStateSkipSignatureSetMap =
new HashMap<SignedOperationNameEnum, List<T>>();
}
To introduce method with generics just write: 要介绍具有泛型的方法,只需编写:
private <T extends ParentObject> Map<SignedOperationNameEnum, List<T>> operationToOrderStateSkipSignatureSetMap() {
return new HashMap<>();
}
I believe the problem is in the types you are using for instance this code which is very similar to yours compiles and runs perfectly on 1.7. 我相信问题出在您正在使用的类型中,例如与您的代码非常相似的代码,它们可以在1.7上完美运行。
public class SomeClass {
static <T extends Number> Map<Integer, List<T>> operationToOrderStateSkipSignatureSetMap() {
return null;
}
public static void main(String[] args) throws IOException {
System.out.println(operationToOrderStateSkipSignatureSetMap());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.