是否可以创建一个包含类的新实例的ArrayList,然后使用该ArrayList访问给定类中的方法?这是一个使它更加清楚的示例:
ArrayList<myOtherClassName> myClassObjects= new ArrayList<myOtherClassName>();
myClassObjects.add(new myOtherClassName());
myClassObjects.indexOf(1).methodInOtherClass();
但是,这不起作用!
有没有办法实现我想要的?
最佳答案
使用:
ArrayList<myOtherClassName> class1 = new ArrayList<myOtherClassName>();
class1.add(new myOtherClassName());
class1.get(0).methodInOtherClass();
你需要:
调用.get()方法而不是.indexof()
indexof方法返回索引,而不返回列表中的值/对象。
另外,请务必写
List<myOtherClassName> class1 = new ArrayList<myOtherClassName>();
代替
ArrayList<myOtherClassName> class1 = new ArrayList<myOtherClassName>();
ArrayList是List的实现,您应该始终创建接口类型的对象,而不是实现类的对象。
关于java - ArrayList访问类中的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16103182/