如何引用对象 ArrayList 上的元素。在那个对象上调用一些方法

How can I reference to an element on an ArrayList of objects. to invoke some method on that object

如何引用 ArrayList 个对象上的元素以调用该对象上的某些方法。

例如:

//antsNumber is number entered by the user
Ants antsArray[];
antsArray=new Ants[antsNumber];

Ants 对象中有一些方法。如果可能的话我想做这样的事情..

for(int count=0;count<ants.size();count++){
   ants.elementAt(count).plaplapla;
}

我尝试使用 foreach:

for(Ants ant:antsArray){

但它没有用,因为我需要知道这个数组中元素的数量,所以我可以将它发送到其他方法以便轻松访问它。

ants[count] 将引用数组的单个元素(不是 ArrayList)。

如果它是一个 ArrayList,那么语法将是 ants.get(count)

只需使用 for each 循环从数组中获取每个元素,然后调用该方法;

for(Ants ant:antsArray){
    ant.someMethod();
}

或:

for(int i=0; i < antsArray.length; i++){
    antsArray[i].someMethod();
}

这两个代码都允许您在所有对象上调用该方法。

注意: 数组不等同于 ArrayList