关于java泛型方法声明的问题 [英] Question about java generic method declaration
问题描述
关于我的考试修订的Java通用方法声明的快速问题
如果我想声明一种方法,该方法将返回通过考试如
正确答案是这个
静态列表< teach>通过(List< teach>)
这种方式怎么可能?如果不可能为什么?
static< T>列表与LT; T>通过(List< T extends Taught>)
static< T>列表与LT; T>通过(List< T super Taught>)
我尝试过:
我试过这个并且它是正确的,因为它的返回类型是清楚的,即List< teach>
< pre lang =text> static List< teach>传递(List< teach>)
以下类型是不可能的,
static < T>列表与LT; T>传递(List< T extends Taught>)
因为static不能是通用的。移除< T>
前面的static
,您将获得与之前相同的通用函数声明。 :笑:
如果你想使用泛型返回类型(你想要使用它!)那么你需要用Java创建一个泛型类。该类将确定将使用何种类型的返回值。这看起来类似于以下内容:
class MyClass< T> {
public MyClass(){
}
// 棘手的部分
静态< T extends 对象> T传递(Class< T> paramType){
// 此处的代码。
}
}
// 用作
MyClass< string> obj = new MyClass< string>();
您可以更改通用参数以支持非引用类型(primitive,int,double等类型)。但我会把它留给你。 :-)
在Java中创建泛型类型的实例? - 堆栈溢出 [ ^ ]
java - 如何使方法返回类型通用? - 堆栈溢出 [ ^ ]
Just a quick question about Java generic method declaration for my revision for exam
if i want to declare a method that will return list of Taught students who passed the exam like
the right answer is this
static List<taught> passed(List<taught>)
what about this way is it possible ? if not possible why?
static <T> List<T> passed(List<T extends Taught>)
static <T> List<T> passed(List<T super Taught>)
What I have tried:
Ive tried this and it will be correct because its return type is clearly written, that is, List<taught>
static List<taught> passed(List<taught>)
The following type is not possible,
static <T> List<T> passed(List<T extends Taught>)
Because static cannot be generic. Remove the<T>
infront ofstatic
and you are left with the same generic function declaration that you had previously. :laugh:
If you want to use generic return types (which you want to use!) then you need to create a generic class in Java. The class would determine what type of return values would be used. That would look something like the following,
class MyClass <T> { public MyClass() { } // Tricky part static <T extends Object> T passed (Class<T> paramType) { // Code here. } } // Use as MyClass<string> obj = new MyClass<string>();
You can change the generic parameters to support the non-reference types (the primitive, int, double etc. types). But I would leave that upto you. :-)
Create instance of generic type in Java? - Stack Overflow[^]
java - How do I make the method return type generic? - Stack Overflow[^]
这篇关于关于java泛型方法声明的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!