簡體   English   中英

Java:遍歷數組列表

[英]Java: Iterating through an Array List

我有一個ArrayList,其中包含要在其上執行方法'count'的實例化對象的名稱。 我不確定是否/如何做到這一點。 我有一個循環來掃描數組列表,並添加了偽代碼和我要實現的目標。

    n = 0;
    while(n <= arrayList.size()){
        (arrayList.get(n)).count();
    }

我是Java的新手,並且不確定是否有可能,但是任何幫助將不勝感激。 謝謝。

更簡單的方法...

ArrayList<MyObject> list = ...
for( MyObject obj : list)
  obj.count()

您有幾種方法可以這樣做:

Basic1:

n = 0;
while (n < arrayList.size()) {
    (arrayList.get(n)).count();
    n++;
}

Basic2:

for (int i = 0; i < arrayList.size(); i++) {
    (arrayList.get(i)).count();
}

Better1:

for(ClassTypeOfArrayList item: arrayList) {
    item.count();
} 

Better2:

Iterator iterator = arrayList.iterator();
while(iterator.hasNext()){
    System.out.println(iterator.next());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM