kurumkan
kurumkan

Reputation: 2725

How implement method with List that contains generic parameter with parameter

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.

Upvotes: 0

Views: 41

Answers (2)

samjaf
samjaf

Reputation: 1053

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.

Upvotes: 1

Guillaume Barr&#233;
Guillaume Barr&#233;

Reputation: 4228

Change

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

To

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

Upvotes: 0

Related Questions