Click here to Skip to main content
15,746,079 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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>)
Updated 21-Aug-16 11:34am

1 solution

The following type is not possible,
static <T> List<T> passed(List<T extends Taught>)

Because static cannot be generic. Remove the <T> infront of static 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[^]
Share this answer
Mohibur Rashid 21-Aug-16 18:55pm    
Afzaal Ahmad Zeeshan 22-Aug-16 12:34pm    
Thank you, Mohibur Rashid.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900