0

I want to create a class that can be made without any parameters, and has a method that takes a list of any object and behaves like this:

List<String> list1 = Arrays.asList(new String [] {"a","b"});
List<String> result1 = myClass.myMethod(list1);

List<Integer> list2 = Arrays.asList(new String [] {1,2});
List<Integer> result1 = myClass.myMethod(list2);

Here's my attempt after reading briefly about Java generics:

public class myClass<T> {

public List<T> myMethod(List<T> input) {
  ... 
  return input; // just an example
}

Why doesn't this work?

Jamie Cele
  • 27
  • 6
  • What error are you seeing? – pgreen2 Mar 22 '17 at 04:01
  • Cannot make a static reference to the non-static method ..., tried making the method static but that results in more errors – Jamie Cele Mar 22 '17 at 04:03
  • Ahh, I miss read your example. Two things, the class name shoul start with a capital (`MyClass`), second you would need to add the `static` modifier to the method. See my answer below and an example. – pgreen2 Mar 22 '17 at 04:05

1 Answers1

1

I think the problem is that you put the parameter on the class, but really only need it on the method. Try:

public class MyClass {

  // this is a parameterized method
  public static <T> List<T> myMethod(List<T> input) {
    ... 
    return input; // just an example
  }
}
pgreen2
  • 3,601
  • 3
  • 32
  • 59