Boris Horvat
Boris Horvat

Reputation: 573

Generic method that takes List in non generic class

I want to do something like this

private <T extends List<?>> List<?> getFirstFiveElements(T list) {
    //body
}

However when I tray to pass in the arguments it is not working

List<A> a = new LinkedList<A>;
List<B> b = new LinkedList<B>; 
getFirstFiveElements(a);
getFirstFiveElements(b);

so any suggestion how I cam make this work.

Upvotes: 0

Views: 510

Answers (4)

Boris Horvat
Boris Horvat

Reputation: 573

Great 2 second later, I have found the magic combination. Anyway for all of the others who stumble upon this here is what worked for me

     private <T> List<T> getStart(List<T> list)

Upvotes: 1

missingfaktor
missingfaktor

Reputation: 92026

The following should work just fine.

private static <A, T extends List<A>> List<A> getFirstFiveElements(T list) {
   //
}

T serves no useful purpose here, and therefore can be eliminated.

private static <A> List<A> getFirstFiveElements(List<A> list) {
   //
}

If you want the method to return the same type that it takes (i.e. ArrayList for ArrayList, LinkedList for LinkedList), then sorry to tell you, Java's type system is not capable of that.

Upvotes: 1

Matzi
Matzi

Reputation: 13925

Why do you want to use template? Would not be enough to use this:

private List<?> getFirstFiveElements(List<?> list) {
    //body
}

Upvotes: 0

comradelion
comradelion

Reputation: 133

This works for me:

  import java.util.*;

  public class Test {

  private static <T extends List<?>> List<?> getFirstFiveElements(T list) {
    List<Object> result = new LinkedList<Object>();
    for (int i = 0; i < 5 && i < list.size(); i++) {
      result.add(list.get(i));
    }
    return result;
  }

  public static void main(String[] args) {
    List<Integer> a = new LinkedList<Integer>();
    a.add(1);
    a.add(2);
    a.add(3);
    a.add(4);
    a.add(5);
    a.add(6);
    a.add(7);
    System.out.println(getFirstFiveElements(a));
  }

}

Upvotes: 0

Related Questions