[英]Iterating of Generic Collections in Java
我對 Java 非常陌生,並且很難理解 generics、它們的使用方式以及這樣做的語法。
我有以下 class
class MyCustomArray<T>{
private T[] myArray;
// Default Constructor
public ArraySet(){
this.myArray= (T[]) new Object[10];
}
// Method to get array length
public int getSize(){
return this.myArray.length;
}
... some random code
// Method to iterate
public void iterateSomehow(MyCustomArray<? extends T> collection){
// doesn't work
for(T obj: collection){...}
// doesn't work
for(int i=0; i< collection.size(); i++){
T nextObj= collection[i];
}
}
}
這是針對 class 分配的,它不允許使用像ArrayList
這樣的標准類。 我覺得我在這里缺少一些基本的東西,但不知道是什么。
我的方法錯了嗎? 它只是語法嗎?
更多上下文:
我的直接目標是檢查給定collection
object 中的每個值(顯然是偽代碼):
for( int i=0; i < collection.length; i++ ):
value = collection[i];
if (value == badValue):
// whatever
只有 arrays 可以使用[]
語法進行索引,並且只有 arrays 或實現Iterable
的類可以用於增強型 for 循環的右側( for (T xxx: yyy)
)。 您的 class 不是數組,也沒有實現Iterable
,因此您的嘗試都沒有奏效。
您的 class 包含一個數組 - myArray
。 你可以遍歷它。 這兩個都很好:
for(T obj: collection.myArray){...}
// or
for(int i=0; i< collection.getSize(); i++){
T nextObj= collection.myArray[i];
}
我也覺得你的方法不應該有參數,而是應該迭代this
(如果這實際上是家庭作業的要求,那就無濟於事了):
for(T obj: myArray){...}
for(int i=0; i< getSize(); i++){
T nextObj= myArray[i];
}
您不能直接迭代集合(因為它只是對象),您應該訪問 myArray。 你也可以實現 Iterable 接口,它允許你像這樣
for(T obj: collection){...}
https://www.geeksforgeeks.org/java-implementing-iterator-and-iterable-interface/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.