Reputation: 23
Is it possible to create an ArrayList that contains new instances of a Class and then use that ArrayList to access methods in the given class? Here is an example to make it more clear:
ArrayList<myOtherClassName> myClassObjects= new ArrayList<myOtherClassName>();
myClassObjects.add(new myOtherClassName());
myClassObjects.indexOf(1).methodInOtherClass();
This, however, doesn't work! Is there a way to achieve what I want?
Upvotes: 0
Views: 1869
Reputation: 147
@Oliver-R...
Try Below Code
ArrayList<myOtherClassName> myClassObject = new ArrayList<myOtherClassName>();
myClassObject.add(new myOtherClassName());
myClassObject.get(0).methodInOtherClass();
the method methodInOtherClass() return type is void it will not return any thing other
Upvotes: 0
Reputation: 3181
Use:
ArrayList<myOtherClassName> class1 = new ArrayList<myOtherClassName>();
class1.add(new myOtherClassName());
class1.get(0).methodInOtherClass();
You need to:
indexof method returns the index, and not the value/object from the list.
Also, Always write
List<myOtherClassName> class1 = new ArrayList<myOtherClassName>();
instead of
ArrayList<myOtherClassName> class1 = new ArrayList<myOtherClassName>();
ArrayList is a implementation of List, you should ALWAYS create object of type interface rather than of the implementation class.
Upvotes: 2
Reputation: 9202
Don't use class as variable.
indexOf()
will return an integer. Use get()
instead
ArrayList<myOtherClassName> mylist = new ArrayList<myOtherClassName>();
mylist.add(new myOtherClassName());
mylist.get(0).methodInOtherClass();
Upvotes: 1