Rafi Rafi - 8 months ago 26
Java Question

The method add(T) in the type ArrayList<T> is not applicable for the arguments (T)

I'm learning about the generics and ArrayList. I'm trying to create a generic

method that will take objects as parameter and add them in my
.However, if I declare my method as
public <T> void add1 (T object)
, I get an error when I try to use
method of the
saying that it is not applicable for
arguments (T)
.I'll appreciate if someone can explain me.Code snippet is in the following:

public class Set<T>
ArrayList<T> list;

public Set()
list = new ArrayList<T>();

public <T> void add1 (T object)


From OP's description, list is declared as:

ArrayList<T> list;

The <T> here has to have been declared at class-level, e.g.

class MyClass<T> {
  ArrayList<T> list = new ArrayList<>();

  // ...

So, if the add1 is declared as:

public  <T>  void add1 (T object)

then this declares a new type variable called T: the two Ts here are separate. It is no different to if they had been declared with different names:

ArrayList<T> list = new ArrayList<>();

public <S> void add1(S object) { ... }

which you would not expect to be type-safe.

Remove the <T> declared on add1, to allow the class-level variable to be used in the method.