0

Suppose we have an interface:

public interface MyInterface<Key>
{
    Key getKey();
}

Then we got two classes:

 public class ClassWithString implements MyInterface<String>
 {....................}
 public class ClassWithInteger implements MyInterface<Integer>
 {....................}

How to make something like this:

public static Map convert(List<? extends  MyInterfac<K>> list)
{
    .....
}

Actually I need a method that

  1. can work with lists.
  2. Elements of the list has to extend MyInterface with parameter. How to make that parameter?:

    (List<? extends  MyInterfac<K>> list)
    

Of course convert method wouldn't run, I just wish to implement something like that.

2 Answers 2

1

Try this:

public static <T extends MyInterface<F>,F> Map<F,T> convert (List<T> list){
    return null;
}

edit: Generic methods enable you to pass Type parameters to methods. In your case, you need a Type T extending MyInterface, and the generic Type F of the interface itself. Using both parameters, you can even parameterize the map. The JVM will infer the types wherever it can. In cases where the JVM can't infer the types, you may need to manually cast the return type.

Sign up to request clarification or add additional context in comments.

1 Comment

Code dumps are not useful answers. Say what you did, and why.
0

Change

    public static Map convert(List<? extends  MyInterfac<Key>> list)

To

    public static Map convert(List<? extends  MyInterfac<?>> list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.