I have a function which takes a generic ArrayList<?> as one of the parameters and what I’ve found is that I get a Java error when I try to use the add method of the ArrayList
no suitable method found for add(MyClass)
What I am trying to accomplish is pass parameters for a Class and an ArrayList and have the function populate the ArrayList with objects of the Class. Though if I could instead create and return the ArrayList from my function, that would be fine too (one less parameter would be nice).
Here is some code to illustrate how I am currently trying to go about this:
public void myFunction(Class clazz, ArrayList<?> myList)
{
Object myObject=null;
try{myObject = clazz.newInstance();}catch(Exception e){}
myList.add(myObject);
}
… or maybe something like this:
public ArrayList<?> myFunction(Class clazz)
{
ArrayList<clazz> myList = new ArrayList<clazz>();
Object myObject=null;
try{myObject = clazz.newInstance();}catch(Exception e){}
myList.add(myObject);
}
If someone could please:
a) show me some code that does this
b) explain how to accomplish my goal using Generics
or c) just let me know where I’m going wrong and provide an alternate way
Your first method can be fixed as:
The second one as:
Here
Tis called a type parameter. You can use any letter or identifier instead ofT.